This is a QT question about using QDataStream and QTemporaryFile in C++ and Linux.
I am having some issues getting a QDataStream to flush. QTextStream has a flush function, however QDataStream apparently doesn't need one. (Citation from 2013: http://www.qtcentre.org/threads/53042-QDataStream-and-flush()). My question is, is this actually/still the case, and is there anyway to force a QDataStream to flush?
When I process the file that I have written using QDataStream the last number of writes are missing (112 Bytes when writing 5 bytes at a time, 22 bytes when writing 1 Byte at a time). However, if I write a large quantity of padding to the end of the file then all of the contents is present (except for the last few writes of the padding). This is why I believe the QDataStream is not being flushed to the file.
The files I am processing are medium size raw binary files (Around 2MB).
Here a minimal example using some of the code I have for processing the files:
void read_and_process_file(QString &filename) {
QFile inputFile(filename);
if (!inputFile.open(QIODevice::ReadOnly)) {
qDebug() << "Couldn't open: " << filename;
return;
}
QDataStream fstream(&inputFile);
QTemporaryFile *tempfile = new QTemporaryFile();
if (!tempfile->open()) {
qDebug() << "Couldn't open tempfile";
return;
}
QDataStream ostream(tempfile);
while (!fstream.atEnd()) {
int block_size = 5; //The number to read at a time
char lines[block_size];
//Read from the input file
int len = fstream.readRawData(lines,block_size);
QByteArray data(lines,len);
//Will process data here once copying works
//Write to the temporary file
ostream.writeRawData(data,data.size());
}
process_file(tempfile);
delete tempfile;
}
tempfile->close()
before callingprocess_file(tempfile)
. – hankQTemporaryFile::close
does not delete the file. The file is deleted when theQTemporaryFile
object is destroyed. Also I would suggest not to allocate object inside a single scope usingnew
because that may cause memory leaks. In your example you'll get a leak afterCouldn't open tempfile
. Just allocate your object on stack:QTemporaryFile tempfile;
– hank