C++文本文件操作和二进制文件读写

文本文件操作:
代码如下:

#include <iostream>
#include <fstream>
using namespace std;

void test01()
{
	const char *fileName = "C:\\Users\\Tom\\Desktop\\hhh.txt";
	//ifstream ism(fileName, ios::in);//只读方式打开文件
	ifstream ism;
	ism.open(fileName, ios::in);
	const char *TagetName = "C:\\Users\\Tom\\Desktop\\jjj.txt";
	ofstream osm(TagetName, ios::out);

	if (!ism)
	{
		cout << "打开文件失败" << endl;
		return;
	}

	//读文件
	char ch;
	while (ism.get(ch))
	{
		/*cout << ch;*/
		osm.put(ch);
	}

	ism.close();
	osm.close();

}


int main()
{

	test01();
	return 0;
}

追加写文件操作核心代码:

ofstream osm(TagetName, ios::out | ios::app);

代码如下:

#include <iostream>
#include <fstream>
using namespace std;

void test01()
{
	const char *fileName = "C:\\Users\\Tom\\Desktop\\hhh.txt";
	//ifstream ism(fileName, ios::in);//只读方式打开文件
	ifstream ism;
	ism.open(fileName, ios::in);
	const char *TagetName = "C:\\Users\\Tom\\Desktop\\jjj.txt";
	ofstream osm(TagetName, ios::out | ios::app);

	if (!ism)
	{
		cout << "打开文件失败" << endl;
		return;
	}

	//读文件
	char ch;
	while (ism.get(ch))
	{
		/*cout << ch;*/
		osm.put(ch);
	}

	ism.close();
	osm.close();

}


int main()
{

	test01();
	return 0;
}

二进制文件读写:
对象的序列化: 把对象写入文件
代码如下:

#include <iostream>
#include <fstream>
using namespace std;

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 test01()
{
	const char * fileName = "C:\\Users\\Tom\\Desktop.jjj.txt";
	Person p1(10, 20), p2(30, 40);//二进制存储
	//把p1,p2写进文件里
	ofstream osm(fileName, ios::out | ios::binary);
	osm.write((char*)&p1, sizeof(Person));
	osm.write((char*)&p2, sizeof(Person));

	osm.close();

	ifstream ism(fileName, 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()
{
	test01();
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值