简体   繁体   中英

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.

This should be easily implemented by adding in a timer and a sleep/wait loop, continuously checking if we are still 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.

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?

will the return value of atEnd() accurately reflect the change in file contents?

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 . It just exposes the protected QThread::msleep() function.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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