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;
}
相关推荐
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑2 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
mit6.8242 小时前
[实现Rpc] 通信类抽象层 | function | using | 解耦合设计思想
c++·网络协议·rpc
我真不会起名字啊2 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
水瓶丫头站住3 小时前
Qt的QStackedWidget样式设置
开发语言·qt
小钊(求职中)4 小时前
Java开发实习面试笔试题(含答案)
java·开发语言·spring boot·spring·面试·tomcat·maven
ox00805 小时前
C++ 设计模式-命令模式
c++·设计模式·命令模式
慕诗客5 小时前
QT基于Gstreamer采集的简单示例
开发语言·qt
Blasit5 小时前
C++ Qt建立一个HTTP服务器
服务器·开发语言·c++·qt·http