【发布时间】:2012-04-12 03:38:26
【问题描述】:
我正在尝试了解如何正确地将数据正确写入二进制文件。正在写入数据,但是当回读以进行测试时,很明显我没有正确写入。数据读取/写入如下。
Unsigned Char 告诉下一个字符串有多长,然后写入一个字符串,然后写入一个整数 ID。 (或长度 studentname student_id )。以下是将数据保存到文件的 printList 函数。
void printList(struct node * nptr, string filename){
ofstream myfile;
myfile.open( filename.c_str(), ios::binary );
while(nptr){
myfile.write( (char*) &nptr->data.len, sizeof( unsigned char ) );
myfile.write( (char*) nptr->data.name, len * sizeof(char) );
myfile.write( (char*) &nptr->data.id, sizeof(int) );
//myfile.write( (const char*) &nptr->data, sizeof( Student ) );
nptr = nptr->next;
}
myfile.close();
}
这里是数据存储在链接列表中的学生结构:
struct node{
Student data;
struct node* next;
};
//=== Student struct===//
struct Student{
unsigned char len;
char* name;
int id;
};
//====================//
这是我为读取二进制文件而编写的 loadbin 文件,我又搞砸了,我已经阅读并观看了大量关于此的教程。我真的很难过。
unsigned char len;
char* name;
int id;
int main( int argc, char* argv[] )
{
if( argc > 1 )
{
ifstream f( argv[1] , ios::binary);
while( !f.eof() )
{
f.read( (char*) &len , sizeof( unsigned char ) );
if( f.eof() )
break;
name = new char[len+1];
name[len+1] = '\0';
f.read( (char*) name , len * sizeof( char ) );
f.read( (char*) &id , sizeof( int ) );
cout << (int)len << " " << name << " " << id
<< "\n";
}
}
else
cout << "\nToo few arguments.\n";
}
更多信息,我无法更改文件被重新读入的方式。修复必须来自我写作的时候。我只是把它包括在内,以防万一。
【问题讨论】:
-
你有文件的十六进制转储吗?您能提供一个片段以及用于编写它的原始测试数据吗?
-
您最好能够更改文件被读回的方式......它完全被破坏了。正确的习惯用法是首先尝试读取,然后使用 fail、eof 和/或 gcount(或隐式转换为
bool)评估成功。例如,while (f.read(...)) { name = ...; if (f.read(...) && f.read(...)) cout ... }. Also,name[len+1] = '\0'` 写入 PAST 缓冲区的末尾 - 未定义的行为- 应该是name[len]。另外,if (ofstream of(..., ...)) { for (; nptr; nptr = nptr->next) if (!(f.write(...) && f.write(...) ...)) { cerr << ...; break; }
标签: c++ struct binaryfiles writing