gpt4 book ai didi

c++ - 在 C++ 中读\写结构化二进制文件

转载 作者:太空宇宙 更新时间:2023-11-04 16:26:12 30 4
gpt4 key购买 nike

我想读\写一个具有以下结构的二进制文件:

enter image description here

该文件由“RECORDS”组成。每个“RECORD”都有以下结构:我将以第一条记录为例

  • (红色)起始字节:0x5A(始终为 1 字节,固定值 0x5A)
  • (绿色)LENGTH 字节:0x00 0x16(始终为 2 个字节,值可以更改从“0x00 0x02”到“0xFF 0xFF”)
  • (blue) CONTENT: 十进制值表示的字节数长度字段减去 2。

在这种情况下,LENGHT 字段值为 22(0x00 0x16 转换为十进制),因此 CONTENT 将包含 20 (22 - 2) 个字节。我的目标是一条一条地读取每条记录,并将其写入输出文件。实际上我有一个读函数和写函数(一些伪代码):

private void Read(BinaryReader binaryReader, BinaryWriter binaryWriter)
{
byte START = 0x5A;
int decimalLenght = 0;
byte[] content = null;
byte[] length = new byte[2];

while (binaryReader.PeekChar() != -1)
{
//Check the first byte which should be equals to 0x5A
if (binaryReader.ReadByte() != START)
{
throw new Exception("0x5A Expected");
}

//Extract the length field value
length = binaryReader.ReadBytes(2);

//Convert the length field to decimal
int decimalLenght = GetLength(length);

//Extract the content field value
content = binaryReader.ReadBytes(decimalLenght - 2);

//DO WORK
//modifying the content

//Writing the record
Write(binaryWriter, content, length, START);
}
}

private void Write(BinaryWriter binaryWriter, byte[] content, byte[] length, byte START)
{
binaryWriter.Write(START);
binaryWriter.Write(length);
binaryWriter.Write(content);
}

如您所见,我已经为 C# 编写了它,但我真的不知道如何使用 C++ 编写它。有人可以指出我正确的方向吗?

最佳答案

您需要使用 std::ifstream并打开 binary mode 中的文件(std::ios_base::binary)。

peek非常相似,但如果无法提取任何字符,则返回 eof 而不是 -1。和 read将使您能够将给定数量的字节读入一个值。请注意,您熟悉的某些类型(bytetype[])在 C++ 中不存在或工作方式不同。后者可以使用std::vector,但需要自己定义byte

关于c++ - 在 C++ 中读\写结构化二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11816268/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com