Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
Dan Avatar asked Mar 05 '14 08:03

Dan


2 Answers

It is also possible to read the struct in one step.

i.e. fh.read((char*)&h, sizeof(Header));

like image 184
Marcel Zebrowski Avatar answered Nov 04 '22 06:11

Marcel Zebrowski


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;
}
like image 27
Blaz Bratanic Avatar answered Nov 04 '22 05:11

Blaz Bratanic