c++fstream

Update ifstream object after data is written to its file using ofstream


While testing my code, I faced an issue, that ifstream doesn't get updated when more data is written to its file. So here is a sample code that demonstrates the problem:

    ifstream is(filename);
    string line;
    while (getline(is, line))
        cout << "line: " << line << endl;

    ofstream os(filename, ofstream::out | ofstream::app);
    string additional("additional");
    os << additional;
    os.flush();

    while (getline(is, line))
        cout << "line additional: " << line << endl;

No additional lines were written to stdout, though they are written to the file. I'm not using fstream instead of a couple of if/ofstream because I need it like this for testing purposes.

How to make ifstream "see" the changes in the file?

UPDATE: I cleared the bits using clear method. It works OK on my Ubuntu machine with gcc. But it doesn't work on my Mac OSX with llvm. Do you know how to do it platform independently?


Solution

  • You need to call std::ios::clear on the input stream after the first read. When you read the whole file, it sets the failbit in the stream and will refuse to keep reading, even if the file actually changed in the meantime.

    ifstream is(filename);
    string line;
    while (getline(is, line))
        cout << "line: " << line << endl;
    
    ofstream os(filename, ofstream::out | ofstream::app);
    string additional("additional");
    os << additional;
    os.flush();
    
    is.clear(); //< Now we can read again
    while (getline(is, line))
        cout << "line additional: " << line << endl;