#include<iostream>
#include"fstream"
using namespace std;
/*二进制文件的读写 实现类的序列化*/
class Teacher{
public:
Teacher() //默认构造函数
{
this->age = 33;
strcpy(name, "");
}
Teacher(int age, char *name)
{
this->age = age;
strcpy(this->name, name);
}
void printf()
{
cout << "age=" << age << "\n name=" << name << endl;
}
private :
int age; //年龄
char name[30]; //姓名 采用数组形式 采用数组指针会变得很麻烦
};
int main()
{
ofstream fpo("f://binary.txt", ios::binary); //建立一个输出流对象和文件关联 以二进制方式打开文件
if (fpo.fail())
{
cout << "文件读取失败" << endl;
}
Teacher t1(21, "t21"), t2(22, "t22");
fpo.write((char *)(&t1), sizeof(Teacher));
fpo.write((char *)(&t2), sizeof(Teacher)); //写入类
fpo.close();
ifstream fpi("f://binary.txt");
if (fpi.fail())
{
cout << "文件读取失败" << endl;
}
Teacher t;
fpi.read((char *)(&t),sizeof(Teacher));
t.printf();
fpi.read((char *)(&t), sizeof(Teacher));
t.printf();
#include<iostream>
#include"fstream"
using na