Reading Binary File into a Structure (C++)

后端 未结 5 857
遇见更好的自我
遇见更好的自我 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:13

    Without seeing the code that writes the data, I'm guessing that you write the data the way you read it in the first example, each element one by one. Then each record in the file will indeed be 37 bytes.

    However, since the compiler pads structures to put members on nice boundaries for optimization reasons, your structure is 40 bytes. So when you read the complete structure in a single call, then you actually read 40 bytes at a time, which means that your reading will go out of phase with the actual records in the file.

    You either have to re-implement the writing to write the complete structure in one go, or use the first method of reading where you're reading one member field at a time.

提交回复
热议问题