从另一个文件使用std :: fstream写入文件时读取文件 [英] read from a file while another process is writing to it using std::fstream

查看:55
本文介绍了从另一个文件使用std :: fstream写入文件时读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要逐行读取文件,这是通过std :: getline完成的.问题是另一个过程一直在向其附加数据,因此我需要读取新行.

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.

例如,文件首先包含10行,我的程序读取了10行,然后我的程序应等待.过了一会儿,另一个进程将5行添加到文件中,然后我的程序读取了5行.

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);
    }
}

有什么主意吗?谢谢.

推荐答案

当流到达文件末尾并设置错误标志时.设置错误标志后,流将不执行任何读取操作.假设您可以同时读写文件(例如POSIX系统上的情况),则可以 could clear()`状态标志并轮询流.您可能需要进行适当的等待.

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.

没有标准的C ++接口可用于在文件更改时接收某些信号.最好使用适当的IPC机制,例如管道,只要仍然有一个写入过程,该管道在尝试接收更多数据时就会阻塞.

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.

这篇关于从另一个文件使用std :: fstream写入文件时读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆