C++ reading binary data to struct -


i reading binary file know structure of , trying place struct when come read off binary file finding when prints out struc individually seems come out right on fourth read seems add onto last member last read.

here code make's more sense how explaining it:

struc

#pragma pack(push, r1, 1) struct header {     char headers[13];     unsigned int number;     char date[19];     char fws[16];     char collectversion[12];     unsigned int seiral;     char gain[12];     char padding[16];  }; 

main

  header head;   int index = 0;   fstream data;   data.open(argv[1], ios::in | ios::binary);   if(data.fail())     {       cout << "unable open data file!!!" << endl;       cout << "it looks has deleted file!"<<endl<<endl<<endl;       return 0;      }    //check size of head    cout << "size:" << endl;    cout << sizeof(head) << endl;    data.seekg(0,std::ios::beg);        data.read( (char*)(&head.headers), sizeof(head.headers));     data.read( (char*)(&head.number), sizeof(head.number));     data.read( (char*)(&head.date), sizeof(head.date));     data.read( (char*)head.fws, sizeof(head.fws));   //here im testing see if correct data went in.    cout<<head.headers<< endl;    cout<<head.number<< endl;    cout<<head.date<< endl;    cout<<head.fws<< endl;      data.close();     return 0; 

output

size: 96 cf001 d 01.00 0 15/11/2013 12:16:56cf10001001002000 cf10001001002000 

for reason fws seems add head.date? when take out line read head.fws date doesn't have added?

i know thier more data header wanted check data have written correct

cheers

1. date declared as:

char date[19]; 

2. date format 19-characters long:

15/11/2013 12:16:56 

3. , print way:

cout<<head.date 

shortly speaking, try print fixed char[] using address, means, interpreted null-terminated c-string. null-terminated? no.

to solve problem, declare date as:

char date[20]; 

and after fill it, append null terminator:

date[19] = 0; 

it applies members, interpreted string literals.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -