简体   繁体   中英

Is it necessary to flush a QTextStream before closing a QFile?

I need to log some text messages to a file with following requirements :

  1. Each text messages is written in a new line at the end of the file.

  2. Be reasonably sure that each message was correctly written to the file.

So far, the function is using QTextStream and QFile :

bool FileManager::appendLine(const QString &line)
{
    if(!m_file.open(QIODevice::Append | QIODevice::Text)) // m_file is a QFile
        return false;

    QTextStream ts(&m_file);

    ts << line << endl;

    bool status = (ts.status() == QTextStream::Ok);

    m_file.close();

    return status;
}

Point 1 is satisfied but i have doubts about Point 2.

Even Qt Doc says that it is sufficient to close() the QFile to flush all its internal buffers :

void QFileDevice::close()

Reimplemented from QIODevice::close().

Calls QFileDevice::flush() and closes the file. Errors from flush are ignored.

What about the internal buffer of the QTextStream ?

Is it necessary to call QTextStream::flush() before closing the file ?

About Point 2, i guess that reading back the line just after it has been written would be the only way to be 100% sure of that. (for example a power failure may occur while the kernel has still datas in its buffers )

Thanks.

In your case, its not, because you are appending &endl in each write!

  • Writting &endl to the QTextStream writes '\\n' to the stream and flushes the stream. It is Equivalent to: stream << '\\n' << flush;

  • Further, when QTextStream is flushed due to &endl , it will empty all data from its write buffer into the device and call flush() on the device.

While this particular code will work because operations with QTextStream end with an endl , it's still better to ensure that QTextStream is completely and utterly finished working with the file when you close it. Just use scopes.

bool FileManager::appendLine(const QString &line)
{
    if(!m_file.open(QIODevice::Append | QIODevice::Text)) // m_file is a QFile
        return false;
    
    bool status {false};
    {
        QTextStream ts(&m_file);
        
        ts << line << endl;
        
        status = (ts.status() == QTextStream::Ok);
    }
    
    m_file.close();
    
    return status;
}

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