阅读由struct定义的二进制文件 [英] Reading binary file defined by a struct

查看:135
本文介绍了阅读由struct定义的二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能指出我的,我怎么能读取由C结构定义的二进制文件正确的方向?
它具有结构,这使我的事情,这将复杂的事情里面少数的#define。

结构看起来是这样的:(尽管它更大和比这更复杂)

Could somebody point me in the right direction of how I could read a binary file that is defined by a C struct? It has a few #define inside of the struct, which makes me thing that it will complicate things.
The structure looks something like this: (although its larger and more complicated than this)

struct Format {
    unsigned long str_totalstrings;
    unsigned long str_name;
    #define STR_ORDERED 0x2
    #define STR_ROT13 0x4
    unsigned char stuff[4];
    #define str_delimiter stuff[0]
}

我真的AP preciate它,如果有人可以点我就如何做到这一点的正确方向。或者,如果任何孤单教程了那里,涵盖这个主题?

I would really appreciate it if somebody could point me in the right direction on how to do this. Or if theres any tutorial out there that covers this topic?

非常感谢提前对你的帮助。

Thanks a lot in advance for your help.

推荐答案

阅读由struct定义的二进制是容易的。

Reading a binary defined by a struct is easy.

Format myFormat;
fread(&myFormat, sizeof(Format), 1, fp);

#定义不影响在所有的结构。 (里面是把他们一个奇怪的地方,虽然)。

the #defines don't affect the structure at all. (Inside is an odd place to put them, though).

然而,这不是跨平台安全。这是您放心的读写器都使用相同的平台,将可能工作的最简单的事情,在情况。

However, this is not cross-platform safe. It is the simplest thing that will possibly work, in situations where you are assured the reader and writer are using the same platform.

的更好的方式是重新定义的结构,例如:

The better way would be to re-define your structure as such:

struct Format {
    Uint32 str_totalstrings;  //assuming unsigned long was 32 bits on the writer.
    Uint32 str_name;
    unsigned char stuff[4];
};

,然后有一个'platform_types.h的正确的typedef UINT32你的编译器,现在你可以直接读入结构,但排列顺序问题,你仍然需要
做这样的事情:

and then have a 'platform_types.h" which typedefs Uint32 correctly for your compiler. Now you can read directly into the structure, but for endianness issues you still need to do something like this:

myFormat.str_totalstrings = FileToNative32(myFormat.str_totalstrings);
myFormat.str_name =   FileToNative32(str_name);

其中FileToNative要么是无操作或依赖于平台的字节反向。

where FileToNative is either a no-op or a byte reverser depending on platform.

这篇关于阅读由struct定义的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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