C++ 文件和流
全面覆盖 C++ <fstream> 三大文件流类、六种打开模式与默认组合、is_open 状态检查与 RAII 自动关闭、写入/追加/格式化与逐行读取、seekg/seekp/tellg 定位及工程注意事项。
学完这一章,你能够
- 全面覆盖 C++ <fstream> 三大文件流类、六种打开模式与默认组合、is_open 状态检查与 RAII 自动关闭、写入/追加/格式化与逐行读取、seekg/seekp/tellg 定位及工程注意事项。
<fstream> 三大文件流类与打开/关闭机制
除了标准输入输出 `cin`/`cout`,C++ 通过 `<fstream>` 头文件提供磁盘文件读写能力,核心包含 `ofstream`(输出写文件)、`ifstream`(输入读文件)与 `fstream`(双向读写)三个文件流类(见表一)。使用 `std::ofstream outfile("example.txt");` 时,若目标文件不存在通常新建,若已存在则默认截断清空原有内容。
打开文件既可通过构造函数一步完成,也可先构造空流再调用 `open(filename, mode)`;现代 C++ 支持 `std::string` 路径,C++17 起还支持 `std::filesystem::path`。六种打开模式(见表二)可用按位或 `|` 自由组合,如 `ios::out | ios::trunc` 清空写入、`ios::app` 末尾追加、`ios::in | ios::out` 双向读写(注意双向读写默认要求文件已存在,搭配 `trunc` 则会清空)。三类流的默认模式汇总见表三。
由于路径不存在或权限受限随时可能发生,打开文件后务必用 `is_open()` 或流布尔转换(配合 `fail()`、`bad()`)检查状态。文件流遵循 RAII 资源管理:局部流对象离开作用域析构时会自动刷新并关闭文件;若需提前关闭、复用流打开另一文件或校验关闭阶段写入错误,应显式调用 `close()` 并检查流状态。
写入、追加与多种读取方式(>>、getline、read)
借助 `ofstream` 与 `<<` 可像操作 `cout` 一样向文件写出多行文本与数值,完成后调用 `close()` 并核验 `!outfile` 确认刷新无误。默认打开已有文件会覆盖旧内容;若需保留既有数据并在末尾新增记录,必须指定 `std::ios::app` 模式。
`ifstream` 常用三种读取策略:`>>` 按目标类型解析并自动跳过前导空白,但读字符串遇空格即停止;`std::getline(infile, line)` 读取含空格的完整文本行存入 `std::string`(不含末尾换行符);`read()` 面向二进制定长字节块。在交互输入中先用 `cin >>` 读数字再用 `getline` 读整行时,须先清理缓冲区残余换行符。
完整的读写往返流程通常先接收姓名(`getline` 保留空格)与年龄(`>>` 并检查有效输入),由 `ofstream` 写入 `afile.dat` 后显式 `close()` 并检查写入状态,再用 `ifstream` 重新打开逐项读回验证;若在同一 `fstream` 对象上双向读写,则需显式管理读写位置与流状态标志。
文件位置指针、二进制随机访问与工程实践
文件流通过读指针(`g` = get)与写指针(`p` = put)维护当前位置,核心操作 `seekg`/`seekp`/`tellg`/`tellp`(见表四)可配合 `ios::beg`(开头)、`ios::cur`(当前)与 `ios::end`(末尾)三个基准(见表五)完成绝对或相对定位。文本模式在不同平台存在换行符转换,按精确字节偏移随机访问务必启用 `ios::binary`。
在二进制文件 `position.dat`(内容 `ABCDEFGHIJ`)中,`seekg(4, ios::beg)` 定位至第 5 个字符 `E`,`seekg(0, ios::beg)` 回到首字符 `A`;若先前读取触发了 `eofbit`,必须先调用 `clear()` 清除状态标志才能再次成功 `seekg`。以 `ios::binary | ios::ate` 打开后调用 `tellg()` 可获取普通文件字节大小(10 字节),现代 C++17 也可直接调用 `std::filesystem::file_size()`。
工程文件操作须始终落实六点检查:校验打开结果、防范 `ofstream` 默认清空覆盖、明确区分文本与 `ios::binary` 模式、持续检查读写状态、理解相对路径基于当前工作目录而非源码目录、善用 RAII 自动关闭并在必要时主动 `close()`。文本推荐 `std::string` + `std::getline`,随机二进制推荐 `read`/`write`/`seekg`/`seekp`。
<fstream> 三大文件流类
| 文件流类 | 核心用途 |
|---|---|
| ofstream | 输出文件流,向磁盘文件写入数据,文件不存在时可自动创建。 |
| ifstream | 输入文件流,从已有磁盘文件读取数据。 |
| fstream | 双向文件流,同时支持文件读取与写入及随机定位修改。 |
文件打开模式标志(std::ios::openmode)
| 模式标志 | 行为说明 |
|---|---|
| ios::in | 以只读或可读模式打开文件。 |
| ios::out | 以写入模式打开文件。 |
| ios::app | 追加模式,每次写操作均自动定位至文件末尾,保留原有内容。 |
| ios::ate | 打开时立即将初始位置置于文件末尾,后续仍可自由重定位。 |
| ios::trunc | 若文件已存在则打开时截断清空全部旧内容。 |
| ios::binary | 以原始字节二进制模式打开,禁止平台换行符等文本转换。 |
三个文件流类的默认打开模式
| 文件流类 | 默认模式 |
|---|---|
| ifstream | ios::in |
| ofstream | ios::out(通常隐含截断已有文件) |
| fstream | ios::in | ios::out |
文件流位置指针操作函数
| 成员函数 | 作用说明 |
|---|---|
| seekg() | 设置输入流读取位置(get pointer)。 |
| seekp() | 设置输出流写入位置(put pointer)。 |
| tellg() | 查询输入流当前读取位置。 |
| tellp() | 查询输出流当前写入位置。 |
seekg / seekp 偏移定位基准
| 定位基准 | 偏移起点说明 |
|---|---|
| ios::beg | 从文件起始字节(位置 0)向后计算偏移。 |
| ios::cur | 从当前流位置指针处计算正负偏移。 |
| ios::end | 从文件末尾位置向前计算负偏移或定位尾部。 |
在 /tmp 实测 ofstream 覆盖/追加、ifstream getline/>>、二进制 seekg/tellg/file_size 与 fstream clear+seekp 覆写
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main() {
const std::string txt_path = "/tmp/mbsky_ch33_demo.txt";
const std::string num_path = "/tmp/mbsky_ch33_numbers.txt";
const std::string bin_path = "/tmp/mbsky_ch33_pos.dat";
const std::string rw_path = "/tmp/mbsky_ch33_rw.dat";
// 1. ofstream default trunc overwrite, ios::app append, and RAII auto-close
{
std::ofstream out(txt_path);
out << "Old line\n";
}
{
std::ofstream out(txt_path); // truncates previous content
out << "Hello C++\n";
out << "Line two\n";
}
{
std::ofstream app(txt_path, std::ios::app);
app << "Appended line\n";
}
std::vector<std::string> lines;
{
std::ifstream in(txt_path);
std::string line;
while (std::getline(in, line)) {
lines.push_back(line);
}
}
std::ifstream missing("/tmp/mbsky_ch33_nonexistent_file.txt");
bool missing_open = missing.is_open();
std::string act1 = std::to_string(lines.size()) + ":" + lines[0] + "|" + lines[2] +
"|missing=" + (missing_open ? "1" : "0");
const std::string exp1 = "3:Hello C++|Appended line|missing=0";
bool ok1 = (act1 == exp1);
// 2. Formatted extraction (>>) and getline() with spaces
{
std::ofstream out(num_path);
out << "Zara Ali\n100 200\n";
}
std::string read_name;
int a = 0, b = 0;
{
std::ifstream in(num_path);
std::getline(in, read_name);
in >> a >> b;
}
std::string act2 = read_name + ":" + std::to_string(a) + "+" + std::to_string(b);
const std::string exp2 = "Zara Ali:100+200";
bool ok2 = (act2 == exp2);
// 3. Binary seekg / tellg / ios::ate and std::filesystem::file_size
{
std::ofstream bout(bin_path, std::ios::binary);
bout.write("ABCDEFGHIJ", 10);
}
char ch4 = '\0', ch0 = '\0', ch_last = '\0';
std::streampos ate_size = -1;
{
std::ifstream bin(bin_path, std::ios::binary);
bin.seekg(4, std::ios::beg);
bin.get(ch4);
bin.seekg(0, std::ios::beg);
bin.get(ch0);
bin.seekg(-1, std::ios::end);
bin.get(ch_last);
}
{
std::ifstream ate(bin_path, std::ios::binary | std::ios::ate);
ate_size = ate.tellg();
}
auto fs_size = std::filesystem::file_size(bin_path);
std::string act3 = std::string(1, ch4) + std::string(1, ch0) + std::string(1, ch_last) +
"|ate=" + std::to_string(static_cast<long long>(ate_size)) +
"|fs=" + std::to_string(fs_size);
const std::string exp3 = "EAJ|ate=10|fs=10";
bool ok3 = (act3 == exp3);
// 4. Bidirectional fstream: hit EOF, clear() state, seekp() patch, verify
{
std::ofstream init(rw_path, std::ios::binary);
init.write("ABCDEFGHIJ", 10);
}
std::string patched;
{
std::fstream rw(rw_path, std::ios::in | std::ios::out | std::ios::binary);
std::string all;
std::getline(rw, all); // reaches EOF
bool hit_eof = rw.eof();
rw.clear(); // clear eofbit before seeking
rw.seekp(2, std::ios::beg);
rw.put('Z');
rw.flush();
rw.seekg(0, std::ios::beg);
std::getline(rw, patched);
if (!hit_eof) patched = "no_eof";
}
const std::string exp4 = "ABZDEFGHIJ";
bool ok4 = (patched == exp4);
// Clean up temporary files
std::remove(txt_path.c_str());
std::remove(num_path.c_str());
std::remove(bin_path.c_str());
std::remove(rw_path.c_str());
std::cout << "{\n"
<< " \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
<< " \"cases\": [\n"
<< " {\"name\": \"ofstream_trunc_append_and_is_open\", \"expected\": \"" << exp1
<< "\", \"actual\": \"" << act1 << "\", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
<< " {\"name\": \"ifstream_getline_and_formatted_extract\", \"expected\": \"" << exp2
<< "\", \"actual\": \"" << act2 << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
<< " {\"name\": \"binary_seekg_tellg_and_file_size\", \"expected\": \"" << exp3
<< "\", \"actual\": \"" << act3 << "\", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
<< " {\"name\": \"fstream_clear_eof_and_seekp_patch\", \"expected\": \"" << exp4
<< "\", \"actual\": \"" << patched << "\", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
<< " ]\n"
<< "}\n";
return 0;
}
- 在 G++ 13.3.0 C++17 离线容器 /tmp 目录中完成文件截断与追加、带空格文本与整数读取、二进制偏移定位 E/A/J 与 10 字节大小校验以及 EOF 后 clear()+seekp 原地修改 4 项实验并清理临时文件。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:d650a5ed27b31aab03063141777f9aced9b5af3043e3fd66b134eaa24e2a5000
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:7ebb69a12a29ca2d7e3b02ef4ee43d80640bb4b60f4fb10255ac7c2f85da73f8
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
当一个 `std::fstream` 读取到文件末尾后,直接调用 `seekg(0, std::ios::beg)` 为什么往往无效?应如何处理?
展开参考解答
读至末尾会使流置位 `eofbit`(部分读取还会置位 `failbit`),处于错误状态的流会忽略后续定位或读写;必须先调用 `clear()` 清除状态标志,再调用 `seekg`/`seekp` 重新定位。