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];
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++.