C++,文本文件,读取文件

代码演示:

cpp 复制代码
#include<iostream>
using namespace std;
#include<string>
#include<fstream>

void test() {
	//1、包含头文件

	//2、创建流对象
	ifstream ifs;

	//3、打开文件并判断文件是否成功
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}

	//4、读文件
	//第一种方式
	char buf[123] = { 0 };
	while (ifs >> buf)
	{
		cout << buf << endl;
	}

	//第二种方式
	//char buf[123] = { 0 };
	//while (ifs.getline(buf, sizeof(buf)))
	//{
		//cout << buf << endl;
	//}

	//第三种方式
	//string buf;
	//while (getline(ifs, buf))
	//{
		//cout << buf << endl;
	//}

	//第四种方式
	//char c;
	//while ((c = ifs.get() != EOF))
	//{
		//cout << c;
	//}

	//5、关闭文件
	ifs.close();
}

int main() {
	test();

}

运行截图:

相关推荐
Hy行者勇哥2 小时前
Python 与 VS Code 结合操作指南
开发语言·python
麦兜*8 小时前
Swift + Xcode 开发环境搭建终极指南
开发语言·ios·swiftui·xcode·swift·苹果vision pro·swift5.6.3
mit6.8249 小时前
[openvela] Hello World :从零开始的完整实践与问题复盘
c++·嵌入式硬件
萧鼎9 小时前
Python pyzmq 库详解:从入门到高性能分布式通信
开发语言·分布式·python
艾伦~耶格尔10 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
yujkss10 小时前
Python脚本每天爬取微博热搜-终版
开发语言·python
yzx99101310 小时前
小程序开发APP
开发语言·人工智能·python·yolo
啊阿狸不会拉杆11 小时前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
小学生的信奥之路11 小时前
洛谷P3817题解:贪心算法解决糖果分配问题
c++·算法·贪心算法
曙曙学编程12 小时前
stm32——GPIO
c语言·c++·stm32·单片机·嵌入式硬件