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;
}
相关推荐
不良手残12 分钟前
IDEA类和方法注释模板设置-保姆教程
java·开发语言
项目題供诗29 分钟前
黑马python(二十四)
开发语言·python
就改了1 小时前
JUC小册——公平锁和非公平锁
java·开发语言
一粒沙白猫2 小时前
Java综合练习04
java·开发语言·算法
哎呦你好2 小时前
【CSS】Grid 布局基础知识及实例展示
开发语言·前端·css·css3
一入JAVA毁终身2 小时前
处理Lombok的一个小BUG
java·开发语言·bug
Hellyc2 小时前
JAVA八股文:异常有哪些种类,可以举几个例子吗?Throwable类有哪些常见方法?
java·开发语言
2301_803554522 小时前
c++中的绑定器
开发语言·c++·算法
海棠蚀omo3 小时前
C++笔记-位图和布隆过滤器
开发语言·c++·笔记
杰哥技术分享3 小时前
Yii2 安装-yii2-imagine
开发语言·yii