When you speak:
fstream file("file.txt", fstream::in | fstream::out | fstream::app);
you open the file in add mode, i.e. in the end. Just open it in read mode:
fstream file("file.txt", fstream::in );
or use ifstream:
ifstream file("file.txt" );
And of course, as Ervikker suggests, you should always verify that the open has succeeded.
If you are set to open in add mode, you can explicitly move the read pointer:
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { fstream file( "afile.txt", ios::in | ios::out | ios::app ); if ( ! file.is_open() ) { cerr << "open failed" << endl; return 1; } else { file.seekg( 0, ios::beg ); // move read pointer string line; while( getline( file, line ) ) { cout << line << endl; } } }
Edit: It seems that the combination of flags used when opening the file leads to specific behavior. The above code works with g ++ on Windows, but not with g ++ on Linux.
anon
source share