【问题标题】:Writing to file in chunks periodically定期分块写入文件
【发布时间】:2019-04-30 10:22:33
【问题描述】:

目前我正在将一个巨大的QByteArray 写入一个文件用数据填充它之后:

QByteArray my_ba;

// Fill out my_ba in some loops

path = "/some/path.data";
QFile file(path);
file.open(QIODevice::WriteOnly);
file.write(my_ba);
file.close();

由于我的QByteArray 可以按GB 的顺序排列,为了减少内存使用量,我需要将我的QByteArray 写入文件分块。。 p>

Qt 有什么方便的工具可以做到这一点吗?有什么标准做法吗?

【问题讨论】:

  • 这个问题是关于如何编写一个将块写入文件的循环?或者是关于理想的块应该有多大?
  • 为什么不只是在循环时写入文件? open first 做你的循环并在完成后关闭文件。另外,请考虑压缩您的数据。
  • 我认为QTextStream::flush 就是这样做的,但我可能错了。
  • QFile 文件("file.dat"); file.open(QIODevice::WriteOnly); QDataStream out(&file); out

标签: qt qfile qbytearray


【解决方案1】:

我最终定期分块写入文件,如下所示:

for(unsigned int j = 0; j < Count; ++j) {

    // Fill out QByteArray my_ba in every single iteration of the loop

    // ...

    // But write my_ba only periodically and then clear it!
    // period is picked in such a way that writing to file will be done for every 1MB of data
    if( j % period == 0){
            if(file){
                file->write(my_ba);
                file->flush();
                my_ba.clear();
            }
        }

    // ...
}

我在将其内容写入文件后定期执行my_ba.clear() 清除我的QByteArray,因此我的QByteArray 永远不会变大,因此它的内存消耗会减少。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    相关资源
    最近更新 更多