简体   繁体   English

使用QTextStream读取正在写入的文件?

[英]Using QTextStream to read a file that is being written to?

I currently read data from a file line by line like so 我目前正在逐行读取文件中的数据,就像这样

readFile(QFile *file)
{
    QTextStream in(file);
    while(!in.atEnd())
    {
        // Do stuff
    }
}

I need to extend this to handle files that are currently being written to. 我需要扩展它以处理当前正在写入的文件。 The while loop should only exit if nothing has been written to the file for N seconds. 仅当N秒钟内未将任何内容写入文件时, while循环才应退出。

This should be easily implemented by adding in a timer and a sleep/wait loop, continuously checking if we are still atEnd() . 这可以通过添加计时器和睡眠/等待循环,连续检查我们是否仍在atEnd()来轻松实现。 However, the documentation is not very clear whether the return value of atEnd() will change if new data has been appended to the file. 但是, 文档尚不清楚,如果将新数据附加到文件中,则atEnd()的返回值是否会更改。

If I use a QTextStream to read from a file that is being written to, will the return value of atEnd() accurately reflect the change in file contents? 如果我使用QTextStream从正在写入的文件中读取, atEnd()的返回值会准确反映文件内容的变化吗?

will the return value of atEnd() accurately reflect the change in file contents? atEnd()的返回值是否可以准确反映文件内容的变化?

Yes

You can test this by executing the following function: 您可以通过执行以下功能进行测试:

void FileReader::_appendFileTest()
{    
    QFile file("/home/cklein/appendFile");
    file.open(QIODevice::ReadOnly);

    QTextStream in(&file);

    while(true)
    {
        while(!in.atEnd())
        {
            QString line = in.readLine();

            qDebug() << line;
        }
        SleepThread::msleep(1000);
    }
}

Code for SleepThread taken from here . 此处获取的SleepThread代码。 It just exposes the protected QThread::msleep() function. 它只是公开受保护的QThread::msleep()函数。

And while the application is running, type this in the terminal 在应用程序运行时,在终端中键入

~ $ echo "foo" >> appendFile
~ $ echo "bar" >> appendFile

You can see that without resetting or re-opening the file, the atEnd() function returns a false when the file is appended to. 您可以看到,在不重置或重新打开文件的情况下,将文件附加到atEnd()函数atEnd()返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM