read from a file while another process is writing to it using std::fstream [duplicate]

余生颓废 提交于 2021-02-08 03:48:00

问题


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 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.



来源:https://stackoverflow.com/questions/27678477/read-from-a-file-while-another-process-is-writing-to-it-using-stdfstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!