gpt4 book ai didi

c# - 读\写结构化二进制文件

转载 作者:行者123 更新时间:2023-11-30 22:34:04 28 4
gpt4 key购买 nike

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

enter image description here

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

  • (红色)起始字节:0x5A(始终为 1 字节,固定值 0x5A)
  • (绿色)LENGTH 字节:0x00 0x16(总是 2 个字节,值可以从“0x00 0x02”到“0xFF 0xFF”)
  • (蓝色)CONTENT:由 LENGTH 字段的十进制值减去 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);
}

这种方式确实有效。然而,由于我正在处理非常大的文件,我发现它根本没有执行,因为我为每个记录读写了 3 次。实际上我想读取错误数据 block 而不是少量字节并且可能在内存中工作,但我使用 Stream 的经验停止使用 BinaryReader 和 BinaryWriter。提前致谢。

最佳答案

FileStream 已经被缓冲,所以我期望它工作得很好。如果确实需要,您始终可以围绕原始流创建一个 BufferedStream 以添加更多缓冲,但我怀疑这是否会产生重大影响。

你说它“根本没有表现”——它的工作速度有多快??您如何确定 IO 就是您的时间流向?您是否对代码进行了分析?

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

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