Reputation: 11
I am using Visual Studio 2017 to practice C++, I have had some experience of C++ on TurboC++. Trying to create a program that reads and writes from file, I am having trouble when I use the "ios::Ate" while opening the file.
file.open("text.txt", ios::ate);
My code is as follows.
#include "pch.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("text.txt", ios::ate);
char a;
while(1){
cin.get(a);
if (a != '0')
file << a;
else break;
}
file.close();
}
When I run this program, is runs without errors but when I open the file it is empty.
I have tried using ios::out and it works fine but I do not want to truncate the file every time I want to write into it.
Upvotes: 1
Views: 614
Reputation: 4963
You code assumes the file exists. you're not specifying an i/o direction, and you should always check whether an operation, e.g. file.open
, succeeds.
int main()
{
fstream file;
// open or create file if it doesn't exist, append.
file.open("text.txt", fstream::out | fstream::app);
// did the file open?
if (file.is_open()) {
char a;
while (1) {
cin.get(a);
if (a != '0')
file << a;
else break;
}
file.close();
}
}
Upvotes: 1