I have a file in which I have written a structure called "Record".
Here is the struct definition:
1 2 3 4 5
#define IDSIZE 10
struct Record{
char id[IDSIZE];
int score;
};
Here's the code where I wrote to the file:
1 2 3 4 5 6 7
Record record;
char* id = "H12345678";
int score = 50;
record.id = id;
record.score = score;
file.write((constchar*)&record, sizeof(record));
}
Here's a screenshot of the file in windows: http://i.imgur.com/zp1fob5.png
To the left is the id, 9 characters.
To the right, well I'm assuming that's the score that I wrote.
And here's the problem, reading from the binary file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Record record;
fstream file(argv[1], ios::in | ios::binary);
if(!file){
cerr << "Could not open the file." << endl;
return 1;
}
char* id = newchar[IDSIZE];
char* buff = newchar[100]; //buffer to hold the string representation of the score
file.seekg(0, ios::beg);
file.read(id, IDSIZE);
cout << "ID: " << id << endl;
file.read(buff, sizeof(int));
int score = atoi(buff);
cout << "SCORE: " << score << endl;
file.clear();
file.close();
return 0;
The ID reads perfectly.
The score...always returns 0, despite that it should show "50".