二进制文件,我想读\写它具有以下结构的二进制文件:读写在结构C++
该文件由“记录”组成。每个 “RECORD” 具有以下结构:我将使用第一记录如实施例
- (红色)START字节:0x5A(始终为1个字节,固定值0x5A)
- (绿色)LENGTH字节:0×00 0x16 (始终为2个字节,值可以改变从“0×00 0×02”到 “0xFF的为0xFF”)
- (蓝色)含量: 长度字段的十进制值减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++。 有人可以请指出我在正确的方向吗?