如何读取字节块到结构 [英] How to read byte blocks into struct

查看:186
本文介绍了如何读取字节块到结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要处理这个资源文件,至极包一组文件。

I have this resource file which I need to process, wich packs a set of files.

首先,将资源文件列出包含的所有文件,加上一些其它的数据,如在此结构:

First, the resource file lists all the files contained within, plus some other data, such as in this struct:

struct FileEntry{
     byte Value1;
     char Filename[12];
     byte Value2;
     byte FileOffset[3];
     float whatever;
}

所以,我需要读取的块正是这种大小。

So I would need to read blocks exactly this size.

我是用从的FileStream读取功能,但我怎么可以指定结构的大小? 我使用的:

I am using the Read function from FileStream, but how can I specify the size of the struct? I used:

int sizeToRead = Marshal.SizeOf(typeof(Header));

,然后将该值传递给阅读,但我只能读一组的byte [],我不知道如何转换成指定的值(以及我知道如何让单字节值...但不是他们的休息)。

and then pass this value to Read, but then I can only read a set of byte[] which I do not know how to convert into the specified values (well I do know how to get the single byte values... but not the rest of them).

此外,我需要指定一个不安全的情况下,我不知道这是否是正确的或不...

Also I need to specify an unsafe context which I don't know whether it's correct or not...

在我看来,阅读的字节流比我想象中的.NET更严厉的:)

It seems to me that reading byte streams is tougher than I thought in .NET :)

谢谢!

推荐答案

假设这是C#,我woudn't创建一个结构作为一个FileEntry类型。我将取代的char [20]用字符串和使用BinaryReader在一个 - <一个href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx">http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx阅读各个领域。你必须在它被写入的相同的顺序读出的数据。

Assuming this is C#, I woudn't create a struct as a FileEntry type. I would replace char[20] with strings and use a BinaryReader - http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx to read individual fields. You must read the data in the same order as it was written.

是这样的:

class FileEntry {
     byte Value1;
     char[] Filename;
     byte Value2;
     byte[] FileOffset;
     float whatever;
}

  using (var reader = new BinaryReader(File.OpenRead("path")) {
     var entry = new FileEntry {
        Value1 = reader.ReadByte(),
        Filename = reader.ReadChars(12) // would replace this with string
        FileOffset = reader.ReadBytes(3),
        whatever = reader.ReadFloat()           
     };
  }

如果你坚持有一个结构,你应该让你的结构不变,并创建参数的构造函数为每个字段的

If you insist having a struct, you should make your struct immutable and create a constructor with arguments for each of your field

这篇关于如何读取字节块到结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆