64,645
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Student{
public:
string name;
int age;
};
int main() {
Student stu1,stu2,stu3;
stu1.name="David";
stu1.age =20;
stu2.name="John";
stu2.age =22;
stu3.name="Lily";
stu3.age =19;
ofstream outfile("I:\\stu.dat",ios::binary);
outfile.write((char*)&stu1,sizeof(stu1));//写入数据到文件
outfile.write((char*)&stu2,sizeof(stu2));
outfile.write((char*)&stu3,sizeof(stu3));
outfile.close();
ifstream infile("I:\\stu.dat",ios::binary);
Student stu4,stu5,stu6;
infile.read((char*)&stu4,sizeof(stu4));
infile.read((char*)&stu5,sizeof(stu5));
infile.read((char*)&stu6,sizeof(stu6));
cout<<stu4.name<<" "<<stu4.age<<endl;
cout<<stu5.name<<" "<<stu5.age<<endl;
cout<<stu6.name<<" "<<stu6.age<<endl;
infile.close();
return 0;
}
/*
David 20
John 22
Lily 19
Process returned 0 (0x0) execution time : 0.012 s
Press any key to continue.
*/