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;
}
相关推荐
gregmankiw5 分钟前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
roman_日积跬步-终至千里20 分钟前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
秦少游在淮海40 分钟前
C++ - string 的使用 #auto #范围for #访问及遍历操作 #容量操作 #修改操作 #其他操作 #非成员函数
开发语言·c++·stl·string·范围for·auto·string 的使用
const5441 小时前
cpp自学 day2(—>运算符)
开发语言·c++
心扬1 小时前
python生成器
开发语言·python
阿蒙Amon1 小时前
06. C#入门系列【自定义类型】:从青铜到王者的进阶之路
开发语言·c#
虾球xz1 小时前
CppCon 2015 学习:CLANG/C2 for Windows
开发语言·c++·windows·学习
CodeWithMe2 小时前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
蓝婷儿2 小时前
6个月Python学习计划 Day 17 - 继承、多态与魔术方法
开发语言·python·学习
Mikhail_G2 小时前
Python应用变量与数据类型
大数据·运维·开发语言·python·数据分析