问题
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.
回答1:
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 could
clear()` 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.
来源:https://stackoverflow.com/questions/27678477/read-from-a-file-while-another-process-is-writing-to-it-using-stdfstream