答案:C++中使用fstream头文件提供的ofstream、ifstream和fstream类进行文件读写操作,其中ofstream用于写入文件,ifstream用于读取文件,fstream支持同时读写;通过构造对象并传入文件名打开文件,使用.is_open()判断是否成功,写入时可选择默认覆盖或ios::app追加模式,读取时常用getline按行获取内容,操作完成后需调用.close()关闭文件。

在C++中进行文件读写操作,主要使用标准库中的 fstream 头文件,它提供了三个核心类:
- ifstream:用于从文件读取数据(input file stream)
- ofstream:用于向文件写入数据(output file stream)
- fstream:支持读写操作的文件流(可同时读写)
下面详细介绍如何使用这些类进行常见的文件读写操作。
1. 写入文件(ofstream)
使用 ofstream 可以轻松创建或覆盖一个文件,并将数据写入其中。
立即学习“C++免费学习笔记(深入)”;
#include#include using namespace std; int main() { ofstream outFile("example.txt");
if (outFile.is_open()) { outFile << "Hello, this is a test.\n"; outFile << "Second line of text.\n"; outFile.close(); cout << "文件写入成功!\n"; } else { cout << "无法打开文件!\n"; } return 0;}
说明:
- 构造 ofstream 对象时传入文件名,若文件不存在会尝试创建;若存在,默认会清空内容。
- 使用 .is_open() 判断文件是否成功打开。
- 写入完成后应调用 .close() 关闭文件。
2. 读取文件(ifstream)
使用 ifstream 读取已有文件的内容。
立即学习“C++免费学习笔记(深入)”;
#include#include #include using namespace std; int main() { ifstream inFile("example.txt"); string line;
if (inFile.is_open()) { while (getline(inFile, line)) { cout << line << endl; } inFile.close(); } else { cout << "无法打开文件!\n"; } return 0;}
说明:
- getline(inFile, line) 按行读取,保留空格,遇到换行符停止。
- 循环读取直到文件结束(EOF)。
- 同样建议使用 .is_open() 验证文件状态。
3. 以追加模式写入文件
如果不想覆盖原文件内容,可以使用追加模式(app)。
立即学习“C++免费学习笔记(深入)”;
ofstream outFile("example.txt", ios::app); if (outFile.is_open()) { outFile << "This line is appended.\n"; outFile.close(); }常用文件模式标志:
- ios::out - 输出(默认覆写)
- ios::app - 追加模式
- ios::in - 输入(读取)
- ios::binary - 二进制模式
4. 同时读写文件(fstream)
当需要对同一个文件进行读写操作时,使用 fstream 类。
立即学习“C++免费学习笔记(深入)”;
fstream file("data.txt", ios::in | ios::out | ios::app); if (file.is_open()) { file << "Appending new data.\n"; file.seekg(0); // 移动读指针到开头 string line; while (getline(file, line)) { cout << line << endl; } file.close(); }注意: 使用 fstream 时,要合理控制读写指针位置。常用函数:
- .seekg() - 设置读取位置(get pointer)
- .seekp() - 设置写入位置(put pointer)
基本上就这些。掌握 ifstream、ofstream 和 fstream 的基本用法后,就能处理大多数文本文件操作需求。对于二进制文件,只需添加 ios::binary 标志,并使用 .read() / .write() 方法。操作完成后记得关闭文件,避免资源泄漏。











