我想从特定偏移量读取二进制数据。使用seekg读取二进制数据失败
我写以下列方式中的数据:
long RecordIO::writeRecord(Data *record)
{
this->openWrite();
fstream::pos_type offset = file->tellp();
file->write(reinterpret_cast<char*>(record), sizeof(Data));
return (long)offset;
}
偏移返回被存储,以后检索。数据是一个包含数据的结构。
后来我尝试用下面的代码再次读取同样的数据:
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(数据)返回768部分关闭补偿我得到的回复是768和1536。但是,当我检查内容的数据,我得到完整的乱码。我做错了什么? 编辑:
这是结构:
struct Data{
long key;
char postcode[8];
char info1[251];
char info2[251];
char info3[251];
};
这也是我如何填写:
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);
}
顺便说一句,该数据被正确地存储,因为我可以retreive其中一个一,序列化
这就是问题所在。它现在返回正确的数据。 – Ikke 2009-08-20 22:48:21