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();

}

运行截图:

相关推荐
微学AI5 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
豆瓣鸡5 小时前
算法日记 - Day3
java·开发语言·算法
韭菜炒鸡肝天6 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
小王C语言6 小时前
【7. 实现登录注册模块】:实现会话管理、注册/登录/退出 API
网络·c++
Aaron - Wistron7 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy12393102168 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
0566468 小时前
Python康复训练——常用标准库
开发语言·python·学习
骊城英雄8 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#
吾儿良辰8 小时前
一个被BCL遗忘的高性能集合:C# CircularBuffer<T>深度解析
开发语言·windows·c#
昆曲之源_娄江河畔8 小时前
Python如何安装flask, pymssql
开发语言·python·flask·pymssql