C++ <fstream>
详解 C++ 文件流头文件 <fstream> 的类继承结构、五大打开模式(in/out/app/ate/trunc)及文本写入、逐行读取、追加与二进制读写实践,并在 /tmp 临时目录完成真实文件流实测。
学完这一章,你能够
- 详解 C++ 文件流头文件 <fstream> 的类继承结构、五大打开模式(in/out/app/ate/trunc)及文本写入、逐行读取、追加与二进制读写实践,并在 /tmp 临时目录完成真实文件流实测。
<fstream> 概述与文件打开模式
`<fstream>` 是 C++ 标准库中面向磁盘文件读写的流头文件,支持文本与二进制两种访问方式。其中核心类 `std::fstream` 同时继承自 `std::istream` 与 `std::ostream`,兼具输入与输出能力(此外同头文件还提供专用于读取的 `std::ifstream` 与专用于写入的 `std::ofstream`)。通过 `file.open("filename", mode)` 或构造函数即可打开目标文件,常见位掩码模式(可用 `|` 组合)包括:`std::ios::in`(输入/读)、`std::ios::out`(输出/写)、`std::ios::app`(每次写入均追加至文件末尾)、`std::ios::ate`(打开后立即定位至文件末尾,但随后仍可自由移动读写指针)以及 `std::ios::trunc`(打开时清空已有内容),读写二进制原始字节时可再按位或上 `std::ios::binary`。
文本写入、逐行读取与追加实践
写入文本文件时,以 `std::ios::out` 打开目标文件后应立即使用 `if (!file)`(或 `if (!file.is_open())`)校验文件是否成功打开;随后像操作 `std::cout` 一样用 `file << "Hello, World!" << std::endl;` 写入文本,并在操作完成后调用 `file.close()` 刷新并释放句柄(析构函数也会自动关闭,遵循 RAII 原则)。
读取文本文件时,以 `std::ios::in` 打开文件,推荐采用惯用循环 `while (std::getline(file, line))` 逐行读取直至到达文件尾(EOF),可完整保留每行内的空格并避免因末尾空行导致的重复读取陷阱。
若希望在保留原有记录的前提下向文件末尾追加日志或新行,应以 `std::ios::app` 模式打开文件(`std::fstream` 搭配 `std::ios::app` 时会自动隐含输出语义,也可显式写作 `std::ios::out | std::ios::app`)。写入新行后原内容保持完整,新内容紧接在旧行之后。本站离线实验已在 `/tmp` 目录下完整实测写入、逐行读回、追加、`ate`/`trunc` 及二进制结构体读写并在结束后自动清理临时文件。
实测 <fstream> 文本写入、逐行读取、追加模式、ate/trunc 语义及二进制结构体读写
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
struct Record {
int id;
double score;
};
} // namespace lab
int main() {
std::vector<lab::Case> cases;
const std::string txt_path = "/tmp/lab_ch49_example.txt";
const std::string bin_path = "/tmp/lab_ch49_record.bin";
// Case 1: Write text file (ios::out) and read lines back (ios::in + getline)
{
std::fstream out_f;
out_f.open(txt_path, std::ios::out);
out_f << "Hello, World!\n" << "This is a test file.\n";
out_f.close();
}
std::vector<std::string> lines1;
{
std::fstream in_f;
in_f.open(txt_path, std::ios::in);
std::string line;
while (std::getline(in_f, line)) {
lines1.push_back(line);
}
in_f.close();
}
bool ok1 = (lines1 == std::vector<std::string>{"Hello, World!", "This is a test file."});
cases.push_back({
"fstream_write_and_read_lines",
lab::jbool(true),
lab::jbool(ok1),
ok1
});
// Case 2: Append to file (ios::app)
{
std::fstream app_f;
app_f.open(txt_path, std::ios::app);
app_f << "Appending this line to the file.\n";
app_f.close();
}
std::vector<std::string> lines2;
{
std::fstream in_f(txt_path, std::ios::in);
std::string line;
while (std::getline(in_f, line)) lines2.push_back(line);
}
bool ok2 = (lines2.size() == 3) && (lines2[2] == "Appending this line to the file.");
cases.push_back({
"fstream_append_mode",
lab::jbool(true),
lab::jbool(ok2),
ok2
});
// Case 3: ios::ate initial position at EOF & ios::trunc clears file
std::streampos ate_pos = 0;
{
std::fstream ate_f(txt_path, std::ios::in | std::ios::ate);
ate_pos = ate_f.tellg();
}
std::streampos trunc_pos = -1;
{
std::fstream tr_f(txt_path, std::ios::out | std::ios::trunc);
tr_f.close();
std::fstream chk_f(txt_path, std::ios::in | std::ios::ate);
trunc_pos = chk_f.tellg();
}
bool ok3 = (ate_pos > 0) && (trunc_pos == 0);
cases.push_back({
"fstream_ate_and_trunc_modes",
lab::jbool(true),
lab::jbool(ok3),
ok3
});
// Case 4: Binary roundtrip (ios::binary) and /tmp cleanup
lab::Record wrec{7, 98.5}, rrec{0, 0.0};
{
std::fstream bf(bin_path, std::ios::out | std::ios::binary);
bf.write(reinterpret_cast<const char*>(&wrec), sizeof(wrec));
}
{
std::fstream bf(bin_path, std::ios::in | std::ios::binary);
bf.read(reinterpret_cast<char*>(&rrec), sizeof(rrec));
}
int rm1 = std::remove(txt_path.c_str());
int rm2 = std::remove(bin_path.c_str());
bool ok4 = (rrec.id == 7 && rrec.score == 98.5) && (rm1 == 0 && rm2 == 0);
cases.push_back({
"fstream_binary_roundtrip_and_cleanup",
lab::jbool(true),
lab::jbool(ok4),
ok4
});
lab::emit(cases);
return 0;
}
- 在 /tmp 中验证 ios::out/in 逐行一致性、ios::app 追加至 3 行、ios::ate 初始位于 EOF 且 ios::trunc 清零,以及 ios::binary 结构体无损往返并清理临时文件。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:bf97637136996d541cc265894ecd7ce12c93604538bf26bf09d75fa77b045ec4
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:b2785cc6da268ecde1b9532f698244f68f868f2ad2cd9009d90cd011e4974479
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`std::ios::app` 与 `std::ios::ate` 在打开文件时都涉及文件末尾,二者的核心区别是什么?
展开参考解答
`std::ios::ate` 仅在打开文件瞬间把读写位置指针移动到文件尾,之后仍可通过 `seekp`/`seekg` 跳转到任意偏移量覆写;而 `std::ios::app` 强制每次写入操作都在当前文件尾执行,无法覆写已有内容。