I'm trying to read binary data from a specific offset.
I write the data in the following way:
long RecordIO::writeRecord(Data *record)
{
this->openWrite();
fstream::pos_type offset = file->tellp();
file->write(reinterpret_cast<char*>(record), sizeof(Data));
return (long)offset;
}
The offset returned is stored, and retrieved later. Data is a struct with the data.
Later i try to read that same data again with the following code:
Data* RecordIO::getRecord(long offset)
{
openRead();
file->seekg((fstream::pos_type) offset);
Data data;
file->read(reinterpret_cast<char *>(&data), sizeof(Data));
return new Data(data);
}
sizeof(Data) returns 768. Some off the offsets i get back is 768 and 1536. But when I check the contents of the data, i get complete gibberish. Am i doeing something wrong? Edit:
This is the struct:
struct Data{
long key;
char postcode[8];
char info1[251];
char info2[251];
char info3[251];
};
And this is how i fill it:
for(int i = 1; i <= numOfRecords; ++i){
newData.key = i;
newData.postcode[0] = '1' + (rand() % 8);
newData.postcode[1] = '0' + (rand() % 9);
newData.postcode[2] = '0' + (rand() % 9);
newData.postcode[3] = '0' + (rand() % 9);
newData.postcode[4] = ' ';
newData.postcode[5] = 'A' + (rand() % 25);
newData.postcode[6] = 'Z' - (rand() % 25);
newData.postcode[7] = '\0';
for(int j = 0; j < 250; ++j){
newData.info1[j] = '+';
newData.info2[j] = '*';
newData.info3[j] = '-';
}
newData.info1[250] = '\0';
newData.info2[250] = '\0';
newData.info3[250] = '\0';
int offset = file->writeRecord(&newData);
index->setOffset(i, offset);
}
Btw, the data is stored correctly, because i can retreive them one by one, sequentialy