0
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();

}

我可以运行该程序,但我似乎无法将记录附加到二进制文件中。谁能帮我看看。

谢谢

4

3 回答 3

1

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

 writeb.open(filenameb, ios::binary | ios::app);
于 2013-01-12T11:39:01.517 回答
1

问题在下面一行,你需要改变

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

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

因为您已经完成strcat(filenameb,".dat");并且 strcpy insidewriteb.open将“.dat”复制到文件名b,它用“.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

于 2013-01-12T11:39:05.580 回答
0

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

于 2013-01-12T11:40:11.343 回答