A couple of things:
When you are ready to write, you need seekp() , not seekg() , i.e.
mfile.seekp(ios_base::end);
Now the problem is that the calls to getline() will set the flags of the stream (in particular, eof), and as a result the stream is not ready for further operations, first you need to clear the flags!
try the following:
string line; mfile.seekg(ios_base::beg); while( getline(mfile,line) ){ std::cout << line << endl; } mfile.seekp(ios_base::end); // seekp mfile.clear(); // clear any flags mfile << "Line 1" << endl; // now we're good mfile << "Line 2" << endl; mfile << "---------------------------------" << endl; mfile.seekg(ios_base::beg); while( getline(mfile,line) ){ std::cout << line << endl; }
Also, use std :: endl and not "\ n", this will cause the buffers to be flushed to the file using the OS ...
source share