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?
Nawaz' comment is correct. Your read loop iterates until the fstream::operator bool
(of ofile
) 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.
// ...
ofile.clear();
ofile << "stackexchnange" << endl;
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:
tellp // returns the output position indicator
seekp // sets the output position indicator
tellg // returns the input position indicator
seekg // sets the input position indicator
in your case you can use the following line to set output position to the end of the file
ofile.seekp(0, std::ios_base::end);
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
ofile.clear(); //cleanup error and eof flags