我正在尝试了解如何将数据正确地保存到二进制文件中。数据正在写入,但当读回进行测试时,很明显我没有正确写入数据。数据读/写如下。
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";
}
更多信息,我无法更改文件的读回方式。修复必须在我写作时进行。我只是把它包括在内,以防它有帮助。
最佳答案
对于开始,我什至不确定这应该编译,除非你有一个 len
变量在某处 float ,比如在你的最后一个代码段中:
myfile.write( (char*) nptr->data.name, len * sizeof(char) ); // len, what len?
因为 sizeof(char)
总是一个,我更喜欢尽可能明确的表达式,我将三个输出行重写为:
myfile.write ((const char *)(&(nptr->data.len)), 1);
myfile.write ((const char *)(nptr->data.name), nptr->data.len);
myfile.write ((const char *)(&(nptr->data.id)), sizeof(int));
下面是一个完整的程序,展示了如何使用它,它足够相似以至于它会有所帮助,但又足够不同以至于你不能把它作为你自己的作品上交:-)
#include <iostream>
#include <fstream>
struct Student {
unsigned char len;
char *name;
int id;
};
struct node {
Student data;
struct node *next;
};
int main (void) {
// Create dummy list, two nodes.
node *temp = new node();
temp->data.len = 6;
temp->data.name = (char *)"diablo";
temp->data.id = 2;
temp->next = NULL;
node *shortList = new node();
shortList->data.len = 3;
shortList->data.name = (char *)"pax";
shortList->data.id = 1;
shortList->next = temp;
// Write it out.
std::ofstream myfile;
myfile.open ("xyzzy.bin", std::ios::binary);
node *curr = shortList;
while (curr != NULL) {
myfile.write ((const char *)(&(curr->data.len)), 1);
myfile.write ((const char *)(curr->data.name), curr->data.len);
myfile.write ((const char *)(&(curr->data.id)), sizeof(int));
curr = curr->next;
}
myfile.close ();
return 0;
}
如果你运行那个程序然后做一个十六进制转储,你会得到:
addr +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +a +b +c +d +e +f 0123456789abcdef
---- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ----------------
0000 03 70 61 78 01 00 00 00 06 64 69 61 62 6c 6f 02 .pax.....diablo.
0010 00 00 00 ...
0013
我认为它符合您想要的格式。
关于c++ - 从链表的结构部分写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10117063/