当前位置: 首页 > article >正文

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

1.读取文件的步骤:

读文件步骤如下:


1.包含头文件


#include <fstream>


2.创建流对象


ifstream ifs;


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


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


4. 读数据


四种方式读取
5.关闭文件
ifs.close();

读取方法一:

#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;
}

 读取方法二:

#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;
}

第三种读取方法:

#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;
}

第四种读取文件方法:

#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;
}


http://www.kler.cn/a/322135.html

相关文章:

  • CKKS同态加密通用函数近似方法和openFHE实现
  • Unity角色控制及Animator动画切换如走跑跳攻击
  • 如何通过费曼技巧理解复杂主题
  • 操作系统 概论
  • 【Vue.js基础】
  • idea上使用tomcat运行web项目
  • 李宏毅2023机器学习作业HW07解析和代码分享
  • 0-1开发自己的obsidian plugin DAY 4
  • 解锁自动化新境界:KeymouseGo,让键盘和鼠标动起来!
  • MySQL GROUP BY 分区大小写问题解析
  • 简明linux系统编程--互斥锁--TCP--UDP初识
  • C:数据在内存中的存储
  • 机器学习与深度学习的区别:深入理解与应用场景
  • Linux上安装Python环境
  • qt中QTatlewidget类的作用及详细使用方法
  • 网页设计html心得
  • python:基于django的html二维码页面生成功能页面
  • 博主回归!数据结构篇启动
  • Vue下载静态文件
  • 南京服务器测评【浪浪云】