在C++中,使用fstream库中的ifstream、ofstream和fstream类进行文件读写操作,需包含头文件;2. ifstream用于读取文件,ofstream用于写入文件,fstream支持同时读写;3. 可通过构造函数或open()方法打开文件,并用is_open()检查状态;4. 写入文件时默认覆盖原内容,读取时可使用>>操作符按格式提取数据,但遇空格会中断。

在C++中,读取和写入文本文件最常用的方式是使用标准库中的fstream。它提供了三个主要的类:ifstream(输入文件流)、ofstream(输出文件流)和fstream(输入输出文件流),分别用于读取、写入以及同时读写文件。下面详细介绍如何使用这些类进行常见的文件操作。
包含头文件与基本概念
要使用文件流,必须包含头文件。同时,和也常被用到:
#include#include #include
关键类说明:
-
ifstream:从文件读取数据,继承自
istream -
ofstream:向文件写入数据,继承自
ostream -
fstream:支持同时读写文件,继承自
iostream
打开文件并检查状态
可以使用构造函数或open()方法打开文件。建议每次打开后检查是否成功。
立即学习“C++免费学习笔记(深入)”;
std::ifstream file("example.txt");
if (!file.is_open()) {
std::cerr << "无法打开文件!" << std::endl;
return -1;
}
关闭文件使用close():
file.close();
逐行读取文本文件
使用std::getline()可以按行读取内容,适用于处理每行为一条记录的文本文件。
std::ifstream file("data.txt");
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
这种方法能正确读取包含空格的整行内容,不会被空格截断。
按单词或字段读取
如果文件内容以空格分隔,可以直接使用>>操作符提取数据:
std::ifstream file("input.txt");
int a;
double b;
std::string name;
file >> a >> b >> name;
这种方式适合格式固定的配置文件或数据表,但遇到空格会中断读取。
写入文本文件
使用ofstream可轻松写入文件,默认会覆盖原内容:
std::ofstream outFile("output.txt");
outFile << "Hello, World!" << std::endl;
outFile << 123 << " " << 45.6 << std::endl;
outFile.close();
若想追加内容而不是覆盖,打开时指定模式:
std::ofstream outFile("output.txt", std::ios::app);
常见文件打开模式
open()函数第二个参数可指定打开方式:
-
std::ios::in:只读(默认 ifstream) -
std::ios::out:只写(默认 ofstream) -
std::ios::app:追加写入 -
std::ios::ate:打开后定位到末尾 -
std::ios::trunc:打开时清空文件(默认行为)
多个模式可用|组合:
file.open("log.txt", std::ios::out | std::ios::app);
完整示例:读写学生信息
假设有一个students.txt文件,每行包含姓名和成绩:
ZhangSan 89.5 LiSi 92.0 WangWu 78.5
读取并显示平均分的代码:
#include#include #include int main() { std::ifstream file("students.txt"); std::string name; double score, total = 0; int count = 0; while (file >> name >> score) { total += score; ++count; std::cout << name << ": " << score << std::endl; } if (count > 0) { std::cout << "平均分: " << total / count << std::endl; } file.close(); return 0; }
基本上就这些。掌握fstream后,处理配置文件、日志、数据导入导出等任务都会变得简单。注意及时关闭文件、检查打开状态,避免运行时错误。不复杂但容易忽略的是路径问题——确保程序运行目录下存在目标文件,或使用绝对路径。









