【问题标题】:Parsing a qbytearray from a binary file从二进制文件中解析 qbytearray
【发布时间】:2020-05-21 02:04:16
【问题描述】:

我试图读取大约 3000 个二进制文件,每个二进制文件都是用小端写的。我寻找文件偏移量并将整个缓冲区读入一个 qbytearray。

二进制格式为int32 stringlength; (4 字节)字符串字符串名称; + '空'

文件示例:

//09 00 00 00 63 6f 6e 76 65 72 74 65 72 00 05 00 00 00 63 6f 75 6e 74 00
// 9 is the size then string.. then size then string..

QFile file("papers.bin");
if (!file.open(QIODevice::ReadOnly))
    return;

file.seek(file.size() - 266 );

QByteArray binarydata = file.readall();

//09 00 00 00 63 6f 6e 76 65 72 74 65 72 00 05 00 00 00 63 6f 75 6e 74

//循环数据

如何在 qbytearray 中循环数据?

【问题讨论】:

  • 读取前4个字节,即长度,然后读取length字节+不包含在字符串长度中的NUL终止符等。问题出在哪里?你尝试了什么?为什么file.seek(file.size() - 266 );?这不是很清楚。
  • bool QFileDevice::seek(qint64 pos) 只是在文件中寻找字符串长度和字符串大小所在的位置.. qfile 是否可以读取.. 读取一个 qbytearray 一旦它被全部读取?

标签: c++ qfile qbytearray


【解决方案1】:

使用QDataStream 读取块:

QDataStream stream(binarydata);
stream.setByteOrder(QDataStream::LittleEndian);
while (!stream.atEnd()) {
    qint32 length;
    stream >> length;

    QByteArray buf(length, 0);
    stream.readRawData(buf.data(), length);
    QString str = QString::fromUtf8(buf);
    // do something with str

    stream.skipRawData(1); // Skip the 00 byte
}

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 2021-12-21
    • 2014-08-23
    • 2015-12-31
    • 2021-05-19
    • 2023-03-11
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多