不能将记录附加到二进制文件中

Cant append a record to a binary file

本文关键字:二进制文件 记录 不能      更新时间:2023-10-16
struct student
{
int identity;
char name[MAX];
int no_assessment;
char assessmenttask[MAX];
int mark;
};

void appendbfile(char filename [MAX])
{
ofstream writeb;
char filenameb [MAX];
strcpy(filenameb,filename);
student s;
strcat(filenameb,".dat");
cout<<"--------------------------------"
    <<endl
    <<"Begin appending for binary file " 
    <<filenameb
    <<endl
    <<endl;

cout<<"Enter student id: ";
cin>>s.identity;
cout<<"Enter student name: ";
cin>>s.name;
writeb.open(strcpy(filenameb,".dat"),ios::binary);
writeb.seekp(0,ios::end);
writeb.write (reinterpret_cast <const char *>(&s), sizeof (s));
writeb.close();
}

我可以运行程序,但我似乎不能附加一个记录到二进制文件。谁能帮我看一下?

谢谢

问题在下一行,您需要更改

writeb.open(strcpy(filenameb,".dat"),ios::binary);

writeb.open(filenameb, ios::binary);

因为你已经完成了strcat(filenameb,".dat");,并且writeb.open中的字符串将'.dat'复制到filenameb中,filenameb将文件名替换为'.dat'。如果你仔细看,文件'.dat'被创建在与你的程序相同的目录下,其中有你的数据。

也因为你不需要调用seekp(0,ios::end);来移动文件指针到文件的末尾,本质上用ios::app标志打开文件将追加文件到文件的末尾。

writeb.open(filenameb, ios::binary | ios::app);
writeb.write (reinterpret_cast <const char *>(&s), sizeof (s));
writeb.close();

查看文件打开模式:http://en.cppreference.com/w/cpp/io/ios_base/openmode

您需要将ios::app标志传递给open函数:

 writeb.open(filenameb, ios::binary | ios::app);

您还需要在open函数中使用ios::app or