C++程序例:文本文件的读写、二进制文件读写

文本文件的读写

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

void test_A()//创建一个.txt文件并写入内容
{
	//1、包含头文件 #include<fstream>
	//2、创建流对象
	ofstream ofs;
	//3、指定打开方式
	ofs.open("test_A.txt", ios::out);
	//4、写内容
	ofs << "利用ofs对象创建了本文档,并以ios::out方式成功进行写入" << endl;
	ofs << "在第二行继续写入数据" << endl;
	//5、关闭
	ofs.close();
}

void test_B()//读取文件中的内容
{
	//1、包含头文件 #include<fstream>
	//2、创建流对象
	ifstream ifs;
	//3、指定打开方式,并判断是否打开成功
	ifs.open("test_A.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;//比如不存在指定文件等情况
		return;
	}
	//4、读内容,4种方式如下。推荐第三种,其他的作了注释处理
	第一种,初始化一个字符数组,注意初始化的时候有大括号
	//char buf[1024] = { 0 };
	//while (ifs >> buf)
	//{
	//	cout << buf << endl;
	//}
	第二种,与前一种类似
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf, sizeof(buf)))
	//{
	//	cout << buf << endl;
	//}
	//第三种,利用全局函数getline(),注意在vs2019仍需要头文件 #include<string>
	string buf;
	while (getline(ifs, buf))
	{
		cout << buf << endl;
	}
	第四种,一个个读,不推荐
	//char c;
	//while ((c = ifs.get()) != EOF)//EOF:end of file
	//{
	//	cout << c;
	//}

	//5、关闭
	ifs.close();
}
int main()
{
	test_A();//创建一个.txt文件并写入内容
	test_B();//读取文件中的内容
	system("pause");
	return 0;
}

二进制文件的读写

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

class Person
{
public:

	char m_Name[64];
	int m_Age;
};

void test_C() //写入自定义数据Person类对象
{
	ofstream ofs;
	ofs.open("person.txt", ios::out | ios::binary);//二进制写
	Person p = { "小明",28 };
	ofs.write((const char*)&p, sizeof(Person));//强转指针为char型
	ofs.close();
}

void test_D()//读出二进制文件
{
	ifstream ifs;
	ifs.open("Person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}
	Person p;//用相应的数据类型去接收即将读到的数据
	ifs.read((char*)&p, sizeof(Person));
	cout << "从文件中读得:姓名:" << p.m_Name 
	<< "  年龄:" << p.m_Age << endl;
	ifs.close();
}
int main()
{
	test_C();//写入自定义数据Person类对象,打开会发现是二进制乱码
	test_D();//读出二进制文件,读出还是正常的
	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值