C++通过fstream头文件实现txt文件读写,使用ofstream写入、ifstream读取、fstream支持同时读写。首先包含等头文件,写文件时创建ofstream对象并检查是否打开,用按词读取;fstream结合ios::in和ios::out实现读写,操作后需close()。

C++ 读取和写入 txt 文件主要使用 fstream 头文件中的类:ifstream(读文件)、ofstream(写文件)和 fstream(可读可写)。操作简单,适合处理文本数据。
1. 包含头文件和命名空间
开始前需要引入必要的头文件:#include
#include iostream>
#include
using namespace std;
2. 写入txt文件(ofstream)
使用 ofstream 向文件写入内容。如果文件不存在会自动创建,存在则覆盖原内容(除非指定追加模式)。示例代码:
ofstream outFile("data.txt");
if (outFile.is_open()) {
outFile
outFile
outFile.close();
} else {
cout
}
ofstream outFile("data.txt", ios::app);
3. 读取txt文件(ifstream)
使用 ifstream 读取文件内容。可以逐行读取或按词读取。示例:逐行读取
立即学习“C++免费学习笔记(深入)”;
ifstream inFile("data.txt");
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout
}
inFile.close();
} else {
cout
}
string word;
while (inFile >> word) {
cout
}
4. 使用 fstream 同时读写
fstream 支持同时读写,需指定模式。fstream file("data.txt", ios::in | ios::out);
// 先读再写,或根据需要定位
基本上就这些。打开文件记得判断是否成功,操作完要 close()。对于简单的配置或日志记录,txt 文件读写非常实用。











