【STL】C++文本文件读写、二进制文件操作、对象序列化 ifstream ofstream


```cpp
#include<iostream>
#include<fstream>//文件读写
using namespace std;

//文本文件读写
void test01() {
	const char* fileName = "H:\\C++初级练习\\数据结构\\source.txt";
	const char* targetName = "H:\\C++初级练习\\数据结构\\target.txt";
	ifstream ism(fileName, ios::in);//只读方式打开文件
	//或者
	//ifstream ism;
	//ism.open(fileName, ios::in);
	//ofstream osm(targetName, ios::out);//写方式打开文件(每执行一次删除该文件前面的数据)
	ofstream osm(targetName, ios::out|ios::app);//写方式打开文件(在文件数据的末尾追加)

	if (!ism) {
		cout << "打开文件失败!" << endl;
		return;
	}
	//读文件
	char ch;
	while (ism.get(ch)) {
		cout << ch;//读文件
		osm.put(ch);
	}
	//关闭文件
	ism.close();
	osm.close();
}


//二进制文件操作 对象序列化
class Person {
public:
	Person(){}
	Person(int age, int id) :age(age), id(id) {}
	void show() {
		cout << "Age:" << age << "  id: " << id << endl;
	}
public:
	int age;
	int id;
};


void test02() {
	Person p1(10, 20), p2(30, 40);//二进制方式放入内存中的
	//把p1 p2写进文件里
	const char* TargetName = "H:\\C++初级练习\\数据结构\\target.txt";
	ofstream osm(TargetName, ios::out | ios::binary);//以二进制的方式进行读写
	osm.write((char*)&p1, sizeof(Person));//二进制的方式写文件
	osm.write((char*)&p2, sizeof(Person));
	osm.close();

	ifstream ism(TargetName, ios::in | ios::binary);//以二进制的方式读文件
	Person p3,p4;
	ism.read((char*)&p3,sizeof(Person));//从文件读取数据
	ism.read((char*)&p4, sizeof(Person));//从文件读取数据
	p3.show();
	p4.show();
}

int main(void) {
	test02();
	return 0;
}

发布了57 篇原创文章 · 获赞 28 · 访问量 4134

猜你喜欢

转载自blog.csdn.net/weixin_41747893/article/details/102808462