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

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

问题描述

有人可以指出我正确的方向,我如何读取由C结构定义的二进制文件?
它在结构体内部有一些#define,这使我觉得它会使事情变得复杂。

结构看起来像这样:(虽然它比这更大更复杂) / p>

  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]
}

我真的很感激如果有人可以指出我正确的方向如何做到这一点。或者如果这里有任何涵盖这个主题的教程?



非常感谢您的帮助。

解决方案

读取由结构体定义的二进制文件很容易。

 格式化myFormat; 
fread(& myFormat,sizeof(Format),1,fp);

#define根本不影响结构。 (虽然内部是一个奇怪的地方),但是,这并不是跨平台的安全。



在您确信读者和作者使用相同平台的情况下,这是最简单的事情。



更好的方法是重新定义你的结构如下:

  struct Format {
Uint32 str_totalstrings; //假设unsigned long是作者的32位。
Uint32 str_name;
unsigned char stuff [4];
};

然后有一个'platform_types.h',它正确地为您的编译器输入Uint32现在你可以阅读直接进入结构,但是对于符合条件的问题,您仍然需要
来执行以下操作:

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

其中根据平台,FileToNative是无操作或字节反转。


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]
}

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.

解决方案

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];
};

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);

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

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

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