2
votes

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.

1
For the textstream, flush() is unnecessary, it is done with endlMohammad Kanan

1 Answers

1
votes

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.