I have the following code
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(void) {
fstream ofile;
ofile.open("test.txt", ios::in | ios::out | ios::app);
for(string line; getline(ofile, line) ; ) {
cout << line << endl;
}
ofile << "stackexchnange" << endl;
ofile.close();
return 0;
}
test.txt contains
hello world!
stackoverflow
Above code outputs
hello world!
stackoverflow
And after running the code stackexchange is not appending at the end of test.txt. How to read and then write in file?
ofile.clear();before writing to the file, because once you exit from the loop, the stream is set to badbit or something, which you need toclear()before further doing any operation. Well, that is my guess, I'm not sure though.ofile << "stackexchnange" << endl;you would find it failed, telling you something went wrong. If you also test the state before you'll find the stream state is not good even before you try to write anything.std::cerrin the fixed example is not only redundant (stick to the exception, orreturn 1!) but also missing a terminating semicolon...