Reading Binary File into a Structure (C++)

后端 未结 5 859
遇见更好的自我
遇见更好的自我 2021-02-04 15:42

So I\'m having a bit of an issue of not being able to properly read a binary file into my structure. The structure is this:

struct Student
{
    char name[25];
         


        
5条回答
  •  不思量自难忘°
    2021-02-04 16:23

    As you've already found out, the padding is the issue here. Also, as others have suggested, the proper way of solving this is to read each member individually as you've done in your example. I don't expect this to cost much more than reading the whole thing in once performance-wise. However, if you still want to go ahead and read it as once, you can tell the compiler to do the padding differently:

    #pragma pack(push, 1)
    struct Student
    {
        char name[25];
        int quiz1;
        int quiz2;
        int quiz3;
    };
    #pragma pack(pop)
    

    With #pragma pack(push, 1) you tell the compiler to save the current pack value on an internal stack and use a pack value of 1 thereafter. This means you get an alignment of 1 byte, which means no padding at all in this case. With #pragma pack(pop) you tell the compiler to get the last value from the stack and use this thereafter, thereby restoring the behavior the compiler used before the definition of your struct.

    While #pragma usually indicates non-portable, compiler-dependent features, this one works at least with GCC and Microsoft VC++.

提交回复
热议问题