如何将枚举类型数据保存到文件

How to save enum-type data to file?

本文关键字:数据 存到文件 类型 枚举      更新时间:2023-10-16

我有枚举类型的数据,例如:

typedef enum
{
    NULLTYPE = 0U,
    ParameterGetType = 1U,
    ParameterSetType = 2U,
    ParameterStatusType  = 3U,
    EventActionType  = 4U,
    CommandType  = 5U,
    CommandGetType  = 6U,
    CommandSetType  = 7U,
    EquipmentIDGetType   = 15U,
    EquipmentIDSetType   = 16U,
    EquipmentIDStatusType = 17U,
    EventReportGetType  = 18U,
    EventReportSetType  = 19U,
    EventReportStatusType = 20U,
    PeriodicReportType = 21U,
    PeriodicReportGetType  = 22U,
    PeriodicReportSetType  = 23U,
    PeriodicReportStatusType  = 24U,
    CommandResponseType  = 25U,
    CommandResponseGetType  = 26U,
    CommandResponseSetType  = 27U,
    CommandResponseStatusType  = 28U,
    CommandResponseDeletedType  = 29U
}MessageType;
我想使用 QByteArray

和 QFile::write(QByteArray) 将其保存到二进制文件中,
但我不知道数据的长度,以及数据的字节"分布"值,
(如果数据为 1,其他字节的值会为零吗?
我认为它不仅限于qt,如何将数据写入文件?

对于短类型数据(MsgItem->PIN),我将这样做:)

QByteArray bytes;
bytes.append(((MsgItem->PIN)>>8) & 0xff);
bytes.append((MsgItem->PIN) & 0xff);
MsgFile->write(bytes);
MsgFile->flush();

将枚举值转换为固定大小的整数(使用 <cstdint> 和例如 uint16_t ),并执行所需的任何字节顺序操作。