Reading and adding from / to a file using std :: fstream

I am wondering why the following code fragment does not work, it looks pretty straightforward, am I mistaken?
The result of this is: the file is created, but empty if I manually add lines whose lines are shown with this code, but nothing else happens.

#include <fstream> #include <iostream> #include <string> using namespace std; int main(){ fstream mfile("text.txt", ios_base::in | ios_base::out | ios_base::app); mfile.seekg(ios_base::beg); string line; while( getline(mfile,line) ){ std::cout << line << "\n"; } mfile.seekg(ios_base::end); mfile << "Line 1\n"; mfile << "Line 2\n"; mfile << "---------------------------------\n"; mfile.seekg(ios_base::beg); while( getline(mfile,line) ){ std::cout << line << "\n"; } mfile.seekg(ios_base::end); } 
0
source share
1 answer

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 ...

+2
source

Source: https://habr.com/ru/post/1332895/


All Articles