Recently a question appeared in MSDN Visual C++ forum regarding the mess ups happned in reading and writing to file. The problem was very simple. I read the file till the end, after that I tried to write to the same file using the same pointer. there’s no problem with file open and it’s rights. What could be the problem.

as the question is simple, the answer too and it should have taken care by the creator of C++ libraries.

The following was my answer to the post. 

int main(void){

fstream myfile(“a.txt”,ios::in|ios::out|ios::app);

string line;

//read and go to end of file

while (! myfile.eof() ){

getline(myfile,line);

cout<<line<<endl;

}

myfile.clear(); // clear the flags (eof)

myfile.seekp( ios::end );

/*write to file*/

char *line1=”testing line1″;

char *line2=”testing line2″;

myfile.write(line1,15);

myfile.write(line2,15);

}

eof means, it set as the error flag to the file stream and it will check this flag before do any read or write operation. You have to clear it using clear function

You can see the answer for my question in MSDN forums.