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?
fstream has two positions : input and output. In your case they both are set to the beginning of the file when you open it.
So you have 4 methods:
in your case you can use the following line to set output position to the end of the file
PS i missed ios::app flag. mea culpa. comment of @Nawaz gives the right answer: after reading the whole file it is necessary to call
Nawaz' comment is correct. Your read loop iterates until the
fstream::operator bool
(ofofile
) returns false. Therefore, after the loop, either failbit or badbit must have been set. failbit is set when loop tries to read for the final time but only EOF is left to read. This is completely OK, but you must reset the error state flag before trying to use the stream again.