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

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 filewhile ((c = ifs.get())!=EOF) {cout << c;}//5.关闭文件ifs.close();}int main() {test01();system("pause");return 0;
}

http://www.lryc.cn/news/447571.html

相关文章:

  • 【人工智能】多模态AI:如何通过融合文本、图像与音频重塑智能系统未来
  • 通过重写QStyle控制QT控件样式
  • WPF入门教学十八 动画入门
  • 电信光猫破解记录
  • 鸿蒙界面开发(九):列表布局 (List)
  • 微服务远程调用(nacos及OpenFeign简单使用)
  • Protobuf vs Thrift: 高性能序列化框架的对比与分析
  • LeetCode Hot100 C++ 哈希 1.两数之和
  • Windows下安装Neo4j流程
  • Spring IDEA 2024 自动生成get和set以及toString方法
  • 部署my2sql
  • Android Studio 真机USB调试运行频繁掉线问题
  • 如何通过费曼技巧理解复杂主题
  • Golang优雅关闭gRPC实践
  • Maven笔记(一):基础使用【记录】
  • [vulnhub] Jarbas-Jenkins
  • js设计模式(26)
  • 数据库中, drop、delete与truncate的区别?
  • 2024年项目经理不能错过的开源项目管理系统大盘点:全面指南
  • MATLAB基本语句
  • 委托的注册及注销+观察者模式
  • Jetpack02-LiveData 数据驱动UI更新(类似EventBus)
  • Redis 的 Java 客户端有哪些?官方推荐哪个?
  • 工作笔记20240927——vscode + jlink调试
  • Python | Leetcode Python题解之第433题最小基因变化
  • opengauss使用遇到的问题,随时更新
  • 从环境部署到开发实战:消息队列 RocketMQ
  • 【机器学习(九)】分类和回归任务-多层感知机(Multilayer Perceptron,MLP)算法-Sentosa_DSML社区版
  • 渗透测试-文件上传绕过思路
  • 等保测评中的密码学应用分析