Reading binary file defined by a struct

后端 未结 5 1779
轻奢々
轻奢々 2021-02-11 01:23

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 t

5条回答
  •  臣服心动
    2021-02-11 02:08

    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.

提交回复
热议问题