QFile::flush and QTextStream::flush

Here is a code snippet writing data to a file:

QFile outfile("file.txt");
if (!outfile.open(QIODevice::Append))
{
    exit();
}
QTextStream out(&outfile);
out.setCodec("UTF-8");
for(int i=0;i<100000;i++)
{
     out<<"somedata";
}
outfile.close();

If you press the Ctrl+C keys during the execution of the program, some data would be lost in the file due to the buffering feature of file read/write mechanism. How to flush the data to the file in time? You may come up with the following code:

QFile outfile("file.txt");
if (!outfile.open(QIODevice::Append))
{
    exit();
}
QTextStream out(&outfile);
out.setCodec("UTF-8");
for(int i=0;i<100000;i++)
{
     out<<"somedata";
     outfile.flush();
}
outfile.close();

because QFile::flush() can flush the data to device at calling time. However, if the program is interrupted during running, you may notice the data in file is still not complete. This is because QTextStream still buffers data in the memory before feeding them to QFile. The correct way to flush data from memory to disk is:

QFile outfile("file.txt");
if (!outfile.open(QIODevice::Append))
{
    exit();
}
QTextStream out(&outfile);
out.setCodec("UTF-8");
for(int i=0;i<100000;i++)
{
     out<<"somedata";
     out.flush();
     outfile.flush();
}
outfile.close();

i.e., both QTextStream::flush() and QFile::flush() should be called to write the data to disk file in time.

Posted in

Comments are closed, but trackbacks and pingbacks are open.