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.

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Comments are closed, but trackbacks and pingbacks are open.