【发布时间】:2009-08-20 22:32:12
【问题描述】:
我正在尝试从特定偏移量读取二进制数据。
我是这样写数据的:
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 是一个包含数据的结构体。
稍后我尝试使用以下代码再次读取相同的数据:
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) 返回 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);
}
顺便说一句,数据存储正确,因为我可以一个接一个地检索它们,sequentialy
【问题讨论】: