fstream
<fstream> 提供文件输入输出流,允许程序像操作 cin、cout 一样读写文件。
它包含三类常用文件流:
ifstream:读文件。ofstream:写文件。fstream:读写文件。
头文件与基本特征
#include <fstream>
常见特征:
| 类型 | 方向 | 默认打开方式 |
|---|---|---|
std::ifstream | 输入 | ios::in |
std::ofstream | 输出 | ios::out |
std::fstream | 输入+输出 | `ios::in |
写文件示例
#include <fstream>
int main() {
std::ofstream out("data.txt");
if (!out) {
return 1;
}
out << "hello file" << '\n';
out << 123 << '\n';
return 0;
}
读文件示例
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream in("data.txt");
if (!in) {
std::cerr << "open failed\n";
return 1;
}
std::string line;
while (std::getline(in, line)) {
std::cout << line << '\n';
}
return 0;
}
打开模式
可以通过第二个参数指定打开方式:
| 模式 | 说明 |
|---|---|
ios::in | 读 |
ios::out | 写 |
ios::app | 追加写入(写在末尾) |
ios::trunc | 截断原文件 |
ios::binary | 二进制模式 |
示例:追加写入。
std::ofstream out("log.txt", std::ios::out | std::ios::app);
文件流状态检查
和其他流一样,文件流也有状态位:
good():状态正常。eof():读到文件末尾。fail():读写失败。bad():严重错误。
通常最直接的写法是直接判断流对象:
if (!in) {
// 打开失败或状态错误
}
二进制读写示例
#include <fstream>
int main() {
int value = 1024;
std::ofstream out("num.bin", std::ios::out | std::ios::binary);
out.write(reinterpret_cast<const char*>(&value), sizeof(value));
out.close();
int loaded = 0;
std::ifstream in("num.bin", std::ios::in | std::ios::binary);
in.read(reinterpret_cast<char*>(&loaded), sizeof(loaded));
return 0;
}
使用注意
- 打开文件后先判断是否成功。
- 文本模式与二进制模式用途不同,不要混用。
- 写文件后及时
close()(或依赖析构自动关闭)。 - 路径错误是最常见问题,可先输出当前工作目录做排查。