第五部分-文件操作

本文介绍了C++中如何进行文本文件和二进制文件的读写操作。通过示例代码展示了如何打开、写入、读取文件,并提供了不同方式读取文件内容的方法。对于二进制文件,文章详细解释了如何存储和读取自定义数据类型,如Person类的对象。
摘要由CSDN通过智能技术生成

第五部分-文件操作

5、文件操作

image-20220822205428370

1、文本文件

1.1 写文件

image-20220822205552871

image-20220822205815739

代码实例:

#include<iostream>
using namespace std;
#include<fstream>//头文件包含

//写文件

void test01() {
	//包含头文件 fstream

	//创建流对象
	ofstream ofs;

	//指定打开方式
	ofs.open("text.txt", ios::out);

	//写内容
	ofs << "姓名:张三" << endl;
	ofs << "性别:男" << endl;
	ofs << "年龄:18" << endl;
    
    //关闭文件
    ofs.close();
}

int main() {
	test01();
}

image-20220822210243327

1.2 读文件

image-20220822210432912

代码:

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

void test01() {
	//包含头部文件

	//创建刘对象
	ifstream ifs;
	//打开文件 并且判断是否打开成功
	ifs.open("text.txt", ios::in);
	if (!ifs.is_open()) {
		cout << "文件打开失败" << endl;
		return;
	}
	//读数据
	//第一种
	/*char buf[1024] = { 0 };
	while (ifs >> buf) {
		cout << buf << endl;
	}*/

	第二种
	/*char buf[1024] = { 0 };
	while (ifs.getline(buf, sizeof(buf))) {
		cout << buf << endl;
	}*/

	//第三种
	/*string buf;
	while (getline(ifs, buf)) {
		cout << buf << endl;
	}*/

	//第四种
	char c;
	while ((c = ifs.get()) != EOF) {
		cout << c;
	}
	{

	}

	//关闭文件
	ifs.close();
}

int main() {
	test01();
}

image-20220822211625059

2、二进制文件

image-20220822211719011

1、写文件

image-20220822211708660

代码:

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

class Person {
public:
	char m_Name[64];//姓名
	int m_Age; //年龄
};

void test01() {
	ofstream ofs;

	ofs.open("person.txt", ios::out | ios::binary);

	Person p = { "张三",18 };

	ofs.write((const char*)&p, sizeof(Person));

	ofs.close();
}

int main() {
	test01();
}

总结:

文件输出流对象 可以通过write函数,以二进制方式写数据

2.2 读文件

image-20220822213222499

代码:

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

class Person {
public:
	char m_Name[64];//姓名
	int m_Age; //年龄
};

void test01() {
	ifstream ifs;

	ifs.open("person.txt", ios::in | ios::binary);

	Person p ;

	if (!ifs.is_open()) {
		cout << "文件打开失败 " << endl;
		return;
	}
	//读文件
	ifs.read((char*)&p, sizeof(Person));
	cout << "姓名" << p.m_Name << "年龄" << p.m_Age << endl;

	ifs.close();
}

int main() {
	test01();
}

文件输入流对象,可以通过read函数,以二进制方式读数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值