向二进制文件中追加数据(P315)
#include<iostream>
#include<fstream>
using namespace std;
class CStudent
{
public:
char id[11];
char name[21];
int score;
};
int main()
{
char ch;
cout<<"确定需要向文件中追加新数据吗(Y/N)?";
cin>>ch;
if(ch=='Y'||ch=='y')
{
CStudent stu;
ofstream outFile("student.dat",ios::app|ios::binary);
if(!outFile)
{
cout<<"以追加方式打开文件失败"<<endl;
return 0;
}
cout<<"请输入:学号 姓名 成绩(以Ctrl+Z结束输入)\n";
while(cin>>stu.id>>stu.name>>stu.score);
outFile.write((char*)&stu,sizeof(stu));
outFile.close();
}
return 0;
}

浙公网安备 33010602011771号