vendredi 10 juin 2016

Need help reading binary file to a structure


I really need help on this one. I've tried following the solution of a question that was similar to mine, but the output is wrong.

The file is in little endian. I am running Win7, which is also little endian

I have a struct Header, and I want to read the binary file into the structure. The member types in the struct are defined by the problem.

struct Header
{
    uint16_t marker;
    uint8_t msg_type;
    uint64_t sequence_id;
    uint64_t timestamp;
    uint8_t msg_direction;
    uint16_t msg_len;
};
void parseFile()
{
  Header h;
  ifstream file("example_data_file.bin", std::ios::binary);

  file.read((char*)&h, sizeof(h));

  file.close();
  printf("%u n",(int)h.marker);
  printf("%u n",h.msg_type);
  printf("%u n", h.sequence_id);
  printf("%u n", h.timestamp);
  printf("%u n",h.msg_direction);
  printf("%u n",h.msg_len);
}

However, the output is none sense. I am expecting the first row to be "ST", and the second row to be 1,2 or 3.

21587
1
1
3719304632
0
48

I have also tried reading each member of the struct individually like this

  file.read ((char*)&h.marker, sizeof(h.marker));
  file.read ((char*)&h.msg_type, sizeof(h.msg_type));
  file.read ((char*)&h.sequence_id, sizeof(h.sequence_id));
  file.read ((char*)&h.timestamp, sizeof(h.timestamp));
  file.read ((char*)&h.msg_direction, sizeof(h.msg_direction));
  file.read ((char*)&h.msg_len, sizeof(h.msg_len));

The output is different, but it is still wrong.

Here is the output of the individual reads:

21587
☺
1
1398642639377848

48

I've attached the binary file here http://www.filedropper.com/exampledatafile

I have no idea what im doing wrong, and I've never parsed a binary file before so this is my first time doing it. Please help~

Thanks!


Aucun commentaire:

Enregistrer un commentaire