C++初学 文件读写操作

首先我们先写一下文件,文件写入需要分为五个步骤,一定要谨记哦!

第一步:包含头文件fstream

#include<fstream>//头文件包含

第二步:创建流对象

ofstream ofs;

第三步:指定打开方式

ofs.open("test.txt", ios::out);

第四步:写内容

ofs << "姓名:张三" << endl;
ofs << "性别: 男" << endl;
ofs << "年龄: 18" << endl;

第五步:关闭文件

ofs.close();

完整代码及运行结果如下:

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

void test01() {
	//1.包含头文件fstream
	//2.创建流对象
	ofstream ofs;
	//3.指定打开方式
	ofs.open("test.txt", ios::out);
	//4.写内容
	ofs << "姓名:张三" << endl;
	ofs << "性别: 男" << endl;
	ofs << "年龄: 18" << endl;
	//5.关闭文件
	ofs.close();
}
int main() {


	test01();

	system("pause");
	return 0;
}

结果:

接下来是读文件。读文件有四种方法:

读文件步骤也是五步:

第一步:包含头文件

#include<fstream>

 第二步:创建流对象

ifstream ifs;

第三步:打开文件并判断文件是否打开成功

ifs.open("文件路径",打开方式);

第四步:读数据

读数据我们会写四种不同的方式。

第一种:

//第一种:
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();

完整代码如下:

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

void test02() {
	//1. 包含头文件
	//2.创建流对象
	ifstream ifs;
	//3.打开文件并判断是否打开成功
	ifs.open("test.txt",ios::in);
	if (!ifs.is_open()) {
		cout << "文件打开失败" << endl;
		return;
	}
	//4.读数据
	//第一种:
	/*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) {//EOF --end of file
		cout << c;
	}
	//5.关闭文件
	ifs.close();

}

int main() {
	test02();


	system("pause");
	return 0;

}

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路卿老师

大哥大姐给点吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值