干了这么多年C++开发,每次遇到文件读取还得去问AI,真是惭愧!今天我决定把这些基础的文件操作函数背下来,整理成这份速记指南。
在C++中,文件操作主要依赖于 <fstream> 头文件中的类。掌握文件读取是C++编程中的基础技能之一。
必须掌握的类和头文件
cpp
#include <fstream> // 主要头文件
#include <iostream> // 用于输出信息
#include <string> // 用于读取整行文本
三类文件流:
ifstream:读取文件(输入流)ofstream:写入文件(输出流)fstream:读写文件(双向流)
必须掌握的函数
1. 打开文件
cpp
void open(const char* filename, ios::openmode mode);
示例:
cpp
ifstream fin;
fin.open("data.txt");
2. 判断文件是否打开成功
cpp
bool is_open();
示例:
cpp
if (!fin.is_open()) {
cerr << "打开文件失败!" << endl;
}
3. 关闭文件
cpp
void close();
示例:
cpp
fin.close();
4. 读取文件内容
逐行读取(最常用)
cpp
getline(fin, line); // line 是 string 类型
示例:
cpp
string line;
while (getline(fin, line)) {
cout << line << endl;
}
按空格分隔读取(适合读取数字或单词)
cpp
int num;
while (fin >> num) {
cout << num << endl;
}
逐字符读取
cpp
char ch;
while (fin.get(ch)) {
cout << ch;
}
5. 判断是否读取到文件末尾
cpp
bool eof();
示例:
cpp
while (!fin.eof()) {
getline(fin, line);
cout << line << endl;
}
使用建议
- 推荐优先使用
ifstream读取文本文件 - 读取文本内容时,
getline()是最常用的方法 - 使用完文件后务必调用
close(),避免资源泄露 - 文件路径建议使用绝对路径或确保文件存在于程序运行目录中
完整示例:读取文本文件并逐行输出
cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("example.txt");
if (!fin.is_open()) {
cerr << "无法打开文件!" << endl;
return 1;
}
string line;
while (getline(fin, line)) {
cout << line << endl;
}
fin.close();
return 0;
}
速记口诀
读文件,用
ifstream;打开前,先判断;
读内容,
getline好;结束后,记得
close!
下次再遇到文件读取,直接看这份笔记就行,不用再到处问AI了!