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;
}
相关推荐
小凡子空白在线学习几秒前
8 非静态数据成员默认初始化
开发语言·前端·javascript
大母猴啃编程7 分钟前
C++基础---类和对象(上)
c语言·开发语言·数据结构·c++·学习·算法·青少年编程
倩倩_ICE_王王8 分钟前
PHP安装后Apache无法运行的问题
开发语言·php·apache·httpd.conf
姆路14 分钟前
Qt5和Qt6获取屏幕的宽高,有区别
c++·qt
Amo Xiang31 分钟前
2024 Python3.10 系统入门+进阶(十六):正则表达式
开发语言·python·正则表达式
翔云API31 分钟前
APP集成人脸识别接口-C#人脸识别API接口
开发语言·c#
Hundred billion40 分钟前
【牛客刷题记录】【JAVA】二分查找
java·开发语言
JovaZou44 分钟前
[Python学习日记-35] Python 中的内置函数(上)
开发语言·python·学习
鸽芷咕1 小时前
【Python报错已解决】KeyError: ‘key‘
开发语言·python
懒洋洋大魔王1 小时前
Java面向对象第三章封装与继承练习题
java·开发语言