1 #include<iostream>
2 #include"fstream"
3 using namespace std;
4
5
6 /*二进制文件的读写 实现类的序列化*/
7
8
9 class Teacher{
10
11
12 public:
13 Teacher() //默认构造函数
14 {
15 this->age = 33;
16 strcpy(name, "");
17 }
18 Teacher(int age, char *name)
19 {
20 this->age = age;
21 strcpy(this->name, name);
22 }
23 void printf()
24 {
25 cout << "age=" << age << "\n name=" << name << endl;
26 }
27 private :
28 int age; //年龄
29 char name[30]; //姓名 采用数组形式 采用数组指针会变得很麻烦
30 };
31
32
33
34
35 int main()
36 {
37
38
39 ofstream fpo("f://binary.txt", ios::binary); //建立一个输出流对象和文件关联 以二进制方式打开文件
40
41
42 if (fpo.fail())
43 {
44 cout << "文件读取失败" << endl;
45 }
46
47
48 Teacher t1(21, "t21"), t2(22, "t22");
49
50
51 fpo.write((char *)(&t1), sizeof(Teacher));
52 fpo.write((char *)(&t2), sizeof(Teacher)); //写入类
53
54 fpo.close();
55
56 ifstream fpi("f://binary.txt");
57
58 if (fpi.fail())
59 {
60 cout << "文件读取失败" << endl;
61 }
62 Teacher t;
63 fpi.read((char *)(&t),sizeof(Teacher));
64
65
66 t.printf();
67
68
69 fpi.read((char *)(&t), sizeof(Teacher));
70 t.printf();
71
72 fpi.close(); //关闭文件
73 system("pause");return 0;};