QDataStream and Flush



这是一个关于在C++和Linux中使用QDataStream和QTemporaryFile的QT问题。

我在刷新 QDataStream 时遇到了一些问题。QTextStream具有刷新功能,但是QDataStream显然不需要。(引自2013年:http://www.qtcentre.org/threads/53042-QDataStream-and-flush(((。我的问题是,这是否实际上/仍然如此,并且无论如何都可以强制QDataStream刷新?

当我处理使用 QDataStream 写入的文件时,最后的写入次数丢失(一次写入 5 个字节时为 112 字节,一次写入 1 字节时为 22 个字节(。但是,如果我在文件末尾写入大量填充,则所有内容都存在(填充的最后几次写入除外(。这就是为什么我相信QDataStream没有被刷新到文件。

我正在处理的文件是中等大小的原始二进制文件(大约 2MB(。

下面是一个使用我用于处理文件的一些代码的最小示例:

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;
}

此答案的第一部分与将文件刷新到磁盘的问题无关。


使用!fstream.atEnd()作为while的条件不是一个好主意。请参阅 http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong。我会将while循环更改为:

const int block_size = 5;      //The number to read at a time
char lines[block_size];
int len = 0;
while ( (len = fstream.readRawData(lines,block_size)) > 0) {
QByteArray data(lines, len);
//Will process data here once copying works
//Write to the temporary file
ostream.writeRawData(data,data.size());
}

但是,我看不出使用中间QByteArray的意义.该循环可以简化为:

while ( (len = fstream.readRawData(lines,block_size)) > 0) {
//Write to the temporary file
ostream.writeRawData(lines, len);
}

如果您需要为其他事情处理QByteArray,可以构造一个并使用它,但对ostream.writeRawData的调用不需要使用它。


对于文件未刷新的问题,我建议使用嵌套范围打开文件。该文件应在范围结束时刷新并关闭。

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;
}
// Create a nested scope for the QDataStream
// object so it gets flushed and closed when the 
// scope ends.
{
QDataStream ostream(tempfile);
const int block_size = 5;      //The number to read at a time
char lines[block_size];
int len = 0;
while ( (len = fstream.readRawData(lines,block_size)) > 0) {
QByteArray data(lines, len);
//Will process data here once copying works
//Write to the temporary file
ostream.writeRawData(lines, len);
}
// The QDataStream should be flushed and
// closed at the end of this scope.
}
process_file(tempfile);
delete tempfile;
}

最新更新