读取二进制文件(Qt)

cpp 复制代码
// 文件头结构
struct RecordMsgHeader
{
    unsigned char flag;
    unsigned short length;
    unsigned short sendAddr;
    unsigned short recvAddr;
    unsigned char msgType;
};
cpp 复制代码
// 记录报文结构
struct RecordMsg
{
    RecordMsgHeader  header;
    quint64 frameId;
    quint64 time;
    QByteArray data;
};
cpp 复制代码
void FileAnalyzer::readFile(QString subDir)
{
    QVector<RecordMsg> msgVector;
    QString filePath = subDir + "/0.bin";
    if (!QFile::exists(filePath))
    {
        qDebug() << "文件不存在: " << filePath ;
    }
    else
    {
        qDebug() << "文件存在,开始读取并解析文件: " << filePath;
        // 记录文件
        // 该文件所有的字节流
        /*
        {
            QFile file(filePath);
            file.open(QIODevice::ReadOnly);
            qDebug() << __FILE__ << __LINE__ << file.readAll().toHex();
            file.close();
        }
        */
        QFile file(filePath);
        file.open(QIODevice::ReadOnly);

        while (!file.atEnd())
        {
            // 3字节
            if (file.bytesAvailable() > 3)
            {
                QByteArray head = file.read (3);
                // 第一个字节:0x7E
                if (head.at (0) != 0x7E)
                {
                    break;
                }
                // 第二个字节和第三个字节:长度
                quint8 a = head.at (1);
                quint8 b = head.at (2);
                int length = a + (b << 8);
                // 这一帧的总长度
                //qDebug() << __FILE__ << __LINE__ << length;
                if (file.bytesAvailable() >= length  - 3)
                {
                    RecordMsg msg;
                    // 回退到最开始
                    file.seek (file.pos() - 3);
                    // 这一帧的报文内容
                    QByteArray dataBlock = file.read (length);
                    //qDebug() << __FILE__ << __LINE__ << dataBlock.toHex();
                    /*     给RecordMsg的
                     *     RecordMsgHeader  header;
                     *     quint64 frameId;
                     *     quint64 time;
                     *     赋值
                     */
                    memcpy (&msg, dataBlock.data(), sizeof (RecordMsg) - sizeof (QByteArray));

                    // 我们具体的报文内容
                    char * data_pointer = dataBlock.data() + sizeof (RecordMsg) - sizeof (QByteArray);
                    msg.data = QByteArray (data_pointer,length - sizeof (RecordMsg) + sizeof (QByteArray));
                    //qDebug() << __FILE__ << __LINE__ << msg.data.toHex();
                    /* 我们可以知道:
                     * 一帧就对应一个RecordMsg对象
                     */
                    msgVector.append(msg);
                }
            }
        }
        file.close();
        if(msgVector.count() > 0)
        {
            emit sendOneFileMsg(msgVector);
        }
    }
}

内容就是根据二进制文件的组成,解析出对应的报文内容。