3

I need to read from a file line by line, it's done by std::getline. The problem another process is appending data to it all the time, then I need to read the new lines.

For example, the file contains 10 lines at first, my program read the 10 line, then my program should wait. A while later another process append 5 lines to the file, then my program read the 5 lines.

I tried this but it doesn't work:

int main() {
    ifstream ifs("test.txt");

    string line;
    while(1) {
        while(std::getline(ifs, line)) {
            cout << line << endl;
        }
        Sleep(50);
    }
}

Any idea? Thanks.

aj3423
  • 2,003
  • 3
  • 32
  • 70
  • The other program should signal this piece of code when to read and when to wait – P0W Dec 28 '14 at 16:47
  • Did you try or want to try a locking/signaling mechanism in order to do that instead of `Sleep`? – Deniz Dec 28 '14 at 16:48

1 Answers1

6

When the stream reaches the end of the file and sets an error flag. With error flags being set the stream won't do any read operation. Assuming you can open the file fir simultanous reading and writing (as is e.g. the case on POSIX systems) you couldclear()` the state flags and poll the stream. You'd probably include a suitable wait.

There is no standard C++ interface which can be used to receive some signal upon file changes. It may be preferable to use a proper IPC mechanism like a pipe which would block when trying to receive more data as long as there is still one writing process.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • 1
    Simply added a `ifs.clear()` in the while loop and it works now! It's enough for my simple program, Thanks. – aj3423 Dec 29 '14 at 04:39