Why can't I read and add using std :: fstream on Mac OS X?

Consider the following C ++ program, which takes a file and prints each line. This is a piece of a large program, where I then add to the file, based on what I see.

#include <fstream> using std::fstream; #include <iostream> #include <string> using std::string; int main() { fstream file("file.txt", fstream::in | fstream::out | fstream::app); string line; while (std::getline(file, line)) std::cerr << line << std::endl; return 0; } 

Now apply this version of file.txt (One word on the first line, followed by a newline):

 Rain 

On my machine (Snow Leopard), this does not output anything. Upon closer inspection, the first getline call fails. Oddly enough, this also fails if I add a second line: still nothing is printed

Can anyone solve this mystery?

+2
source share
2 answers

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.

+9
source

You should check if the file was really open:

 if (!file) std::cerr << "Oh dear" << std::endl; 

Update: Actually, the file was probably opened, but is in add mode - see Neii's answer.

Update 2: OK, wrong again. In Leopard g ++, at least the file will not be opened because the app flag is not compatible with the in flag. Thus, the above check will print Oh dear .

In MSVC ++, he goes ahead and opens the file, apparently from the reading position at the beginning, which explains why other people saw his work, and I apologize for doubting their veracity!

+2
source

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


All Articles