C++基础知识:C++中读文件的四种简单方式

1.读取文件的步骤:

读文件步骤如下:

1.包含头文件

#include <fstream>

2.创建流对象

ifstream ifs;

3.打开文件并判断文件是否打开成功

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

4. 读数据

四种方式读取

5.关闭文件

ifs.close();

读取方法一:

cpp 复制代码
#include<iostream>

using namespace std;

#include<fstream>

//包含头文件

//文本文件 读文件

void test01() {
	//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;
	}

	//5.关闭文件

	ifs.close();


}

int main() {
	test01();
	system("pause");
    return 0;
}

读取方法二:

cpp 复制代码
#include<iostream>

using namespace std;

#include<fstream>

//包含头文件


//文本文件 读文件

void test01() {
	//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.getline(buf, sizeof(buf))) {
		cout << buf << endl;
	}
	//5.关闭文件

	ifs.close();


}

int main() {
	test01();
	system("pause");
    return 0;
}

第三种读取方法:

cpp 复制代码
#include<iostream>

using namespace std;

#include<fstream>

#include<string>

//包含头文件


//文本文件 读文件

void test01() {
	//1.包含头文件

	//2.创建流对象

	ifstream ifs;

	//3.打开文件 并且判断是否打开成功

	ifs.open("test.txt",ios::in);

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

	//4.读数据

	//第三种

	string buf;

	while (getline(ifs, buf) ){
		cout << buf << endl;
	}
	//5.关闭文件

	ifs.close();


}

int main() {
	test01();
	system("pause");
    return 0;
}

第四种读取文件方法:

cpp 复制代码
#include<iostream>

using namespace std;

#include<fstream>

#include<string>

//包含头文件


//文本文件 读文件

void test01() {
	//1.包含头文件

	//2.创建流对象

	ifstream ifs;

	//3.打开文件 并且判断是否打开成功

	ifs.open("test.txt",ios::in);

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

	//4.读数据

	char c;

	//如果没有读到文件末尾就一直读。
	//EOF end of file
	while ((c = ifs.get())!=EOF) {
		cout << c;
	}
	//5.关闭文件

	ifs.close();


}

int main() {
	test01();
	system("pause");
    return 0;
}
相关推荐
米罗篮10 分钟前
DSU并查集 & 拓展欧几里得-逆元
c++·经验分享·笔记·算法·青少年编程
谙弆悕博士27 分钟前
【附C++源码】从零开始实现 2048 游戏
java·c++·游戏·源码·项目实战·2048
郑同学的笔记32 分钟前
【Qt教程29】Qt5和Qt6版本对比
开发语言·qt
基德爆肝c语言36 分钟前
Qt 主窗口全家桶:菜单栏、工具栏、状态栏与对话框完全指南
开发语言·qt
XMYX-02 小时前
28 - Go JSON 数据操作
开发语言·golang·json
三*一2 小时前
Mapbox GL JS 自研面要素整形工具开发实录
开发语言·javascript·arcgis·ecmascript
超级小星星3 小时前
C 语言结构体内存对齐深度解析:从概念到实战
c语言·开发语言
狮子座明仔3 小时前
AgentSPEX:当 Agent 框架开始把“控制流“从 Python 里抠出来
开发语言·python
笨笨饿3 小时前
74_SysTick滴答定时器中断
c语言·开发语言·人工智能·单片机·嵌入式硬件·算法·学习方法
科芯创展3 小时前
XZ4058B/C,20V,外置MOS,8.4V/8.7V开关充电芯片 宽范围电源电压:8.9V~20V-(电池充电电压:8.4V/8.7V)
c语言·开发语言