c++structbinaryifstream

Reading binary data into struct with ifstream


I'm trying to read binary data from a file using ifstream.

Specifically, I'm trying to populate this "Header" struct with data read from a file:

struct Header {
    char id[16];
    int length;
    int count;
};
  1. Now, if I read the file in this way, the result is exactly what I want:

    input.read((char*)&hdr, sizeof(hdr));
    
  2. But if I instead read each variable of the struct manually, the results are gibberish:

    input.read((char*)&hdr.id,     sizeof(hdr.id));
    input.read((char*)&hdr.length, sizeof(hdr.length));
    input.read((char*)&hdr.count,  sizeof(hdr.count));
    

My question is, what is happening here that makes these two methods return different results?


Solution

  • As the comment above states, you are probably missing hdr.length and hdr.count. I tried it with gcc 4.8 and clang 3.5 and it works correctly.

    #include <iostream>
    #include <fstream>
    
    #pragma pack(push, r1, 1)
    struct Header {
        char id[15];
        int length;
        int count;
    };
    #pragma pack(pop, r1)
    
    int main() {
      Header h = {"alalalala", 5, 10};
    
      std::fstream fh;
      fh.open("test.txt", std::fstream::out | std::fstream::binary);
      fh.write((char*)&h, sizeof(Header));
      fh.close();
    
      fh.open("test.txt", std::fstream::in | std::fstream::binary);
    
      fh.read((char*)&h.id, sizeof(h.id));
      fh.read((char*)&h.length, sizeof(h.length));
      fh.read((char*)&h.count, sizeof(h.count));
    
      fh.close();
    
      std::cout << h.id << " " << h.length << " " << h.count << std::endl;
    }