C++文本文件读写、二进制文件操作、对象序列化

 1 ```cpp
 2 #include<iostream>
 3 #include<fstream>//文件读写
 4 using namespace std;
 5 
 6 //文本文件读写
 7 void test01() {
 8     const char* fileName = "H:\\C++初级练习\\数据结构\\source.txt";
 9     const char* targetName = "H:\\C++初级练习\\数据结构\\target.txt";
10     ifstream ism(fileName, ios::in);//只读方式打开文件
11     //或者
12     //ifstream ism;
13     //ism.open(fileName, ios::in);
14     //ofstream osm(targetName, ios::out);//写方式打开文件(每执行一次删除该文件前面的数据)
15     ofstream osm(targetName, ios::out|ios::app);//写方式打开文件(在文件数据的末尾追加)
16 
17     if (!ism) {
18         cout << "打开文件失败!" << endl;
19         return;
20     }
21     //读文件
22     char ch;
23     while (ism.get(ch)) {
24         cout << ch;//读文件
25         osm.put(ch);
26     }
27     //关闭文件
28     ism.close();
29     osm.close();
30 }
31 
32 
33 //二进制文件操作 对象序列化
34 class Person {
35 public:
36     Person(){}
37     Person(int age, int id) :age(age), id(id) {}
38     void show() {
39         cout << "Age:" << age << "  id: " << id << endl;
40     }
41 public:
42     int age;
43     int id;
44 };
45 
46 
47 void test02() {
48     Person p1(10, 20), p2(30, 40);//二进制方式放入内存中的
49     //把p1 p2写进文件里
50     const char* TargetName = "H:\\C++初级练习\\数据结构\\target.txt";
51     ofstream osm(TargetName, ios::out | ios::binary);//以二进制的方式进行读写
52     osm.write((char*)&p1, sizeof(Person));//二进制的方式写文件
53     osm.write((char*)&p2, sizeof(Person));
54     osm.close();
55 
56     ifstream ism(TargetName, ios::in | ios::binary);//以二进制的方式读文件
57     Person p3,p4;
58     ism.read((char*)&p3,sizeof(Person));//从文件读取数据
59     ism.read((char*)&p4, sizeof(Person));//从文件读取数据
60     p3.show();
61     p4.show();
62 }
63 
64 int main(void) {
65     test02();
66     return 0;
67 }

 

posted on 2020-11-15 18:48  大湾  阅读(246)  评论(0编辑  收藏  举报

导航