C++文件处理(一):读/写文本文件
前言
C++文件处理与C语言不同,C++文件处理使用的是:流(stream)
C++头文件#include <fstream>
定义了三个类型来支持文件IO👇
- ifstream从一个给定文件中读取数据
- ofstream向一个给定文件写入数据
- fstream可以读写文件(支持ifstream和ofstream的操作)
这些类型提供的操作与我们之前已经使用过的cin
和cout
操作一样。特别是,我们可以使用IO运算符(>>和<<)来读写文件,也可使用getline
从一个ifstream中读取数据。
一、读txt文件
现有cameras.txt
文件,内容如下👇
读取txt文件,并逐行打印
# Camera list with one line of data per camera:
# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]
# Number of cameras: 1
0 PINHOLE 6220 4141 3430.27 3429.23 3119.2 2057.75
// Author: Todd-Qi
// Date: 2020-02-12
#include <iostream>
#include <fstream> // 头文件 For both ifstream and ofstream
#include <string>
using namespace std;
int main() {
string path = "./cameras.txt";
ifstream in_file(path, ios::in); //按照指定mode打开文件
// is_open()函数返回一个bool值,指出与in_file关联的文件是否成功打开且未关闭
if (in_file.is_open()) { // 或者if (in_file)
cout << "Open File Successfully" << endl;
string line;
while(getline(in_file, line)) {
cout << line << endl;
}
} else {
cout << "Cannot Open File: " << path << endl;
getchar();
return EXIT_FAILURE;
}
in_file.close(); // 关闭与in_file绑定的文件,返回void
getchar();
return EXIT_SUCCESS;
}
二、写txt文件
main()函数如下,main()函数之前的部分同上
#include <iostream>
#include <fstream> // 头文件 For both ifstream and ofstream
#include <string>
using namespace std;
int main()
{
string path = "./log.txt";
ofstream out_file(path, ios::out | ios::app); //按照指定mode打开文件
// ofstream out_file(path, ios::out);
if (out_file.is_open()) {
cout << "Open File Successfully" << endl; // 写txt文件的语法同cout控制台打印
out_file << "Have a Nice Day!" << endl; // 区别在于:写文件(ofstream) / 控制台打印(iostream)
} else {
cout << "Cannot Open File: " << path << endl;
getchar();
return EXIT_FAILURE;
}
out_file.close();
getchar();
return EXIT_SUCCESS;
}
三、文件读写的不同mode
使用open
函数打开文件:
void open(const char* filename, int mode)
第一个参数为文件名,第二个参数指定文件打开的模式。文件的打开模式标记代表了文件的使用方式,这些标记可以单独使用,也可以组合使用。
模式标记 | 适用对象 | 描述 |
---|---|---|
ios::out | ofstream/fstream | 存在则会覆盖 |
ios::app | ofstream/fstream | 存在则会在文件末尾添加 (append) |
参考
- C++ Primer 第五版
- Reading from a Text File
- C++ open 打开文件(含打开模式一览表)
分类:
C++文件/流
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人