这是一个关于在QDataStream和Linux中使用QTemporaryFile和C++的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;
}发布于 2017-08-08 15:42:33
这个答案的第一部分独立于将文件刷新到磁盘的问题。
使用!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的调用不需要使用它。
Re.关于文件未被刷新的问题,我建议使用嵌套的作用域来打开文件。文件应该在作用域的末尾被刷新和关闭。
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;
}https://stackoverflow.com/questions/45572181
复制相似问题