输入/输出库
第 31 章导读:iostream 由状态层、格式化层和缓冲层组成;各子条款和头文件的分工;它与 <format>/<print>、<cstdio>、<filesystem> 的关系。
本节要点
- 一个 iostream 流由三层组成:
basic_streambuf负责缓冲和搬运字符,ios_base/basic_ios保存状态和格式,basic_istream/basic_ostream在值和字符之间转换。 - 换掉流缓冲区,同一个
ostream就能写字符串、文件或终端;格式状态留在流对象上。 - 状态位记录已经发生的事,
eofbit表示某次读取撞到了末尾,所以读循环要以提取本身为条件。 std::format、std::print取代的是格式化层,字符仍然经由流缓冲区或 C 的FILE*写出。<filesystem>也在这一章,但它处理路径和目录,不读写文件内容。
三层结构#
#include <iostream>
#include <sstream>
int main() {
std::stringbuf sb; // 缓冲层:字符存进 string
std::ostream out(&sb); // 格式化层和状态层
out << std::hex << 255;
std::cout << sb.str() << '\n'; // ff
out.rdbuf(std::cout.rdbuf()); // 换成 stdout 的缓冲区
out << 255 << '\n'; // ff:hex 还在 out 上
}out 本身不知道字符最终去了哪里。它把 255 按十六进制变成字符 ff,交给自己指向的流缓冲区;换了缓冲区,输出目的地就变了,而 hex 这个格式标志仍然留在 out 上。
一次 cout << 42 依次经过三层:
用户代码: cout << 42; cin >> x;
│ │
┌─────────────────┴────────────────────┴───────────────┐
│ basic_ostream / basic_istream [iostream.format] │ 值 ↔ 字符:
│ operator<< / >>、put/write、get/read/getline │ sentry、num_put/num_get
├───────────────────────────────────────────────────────┤
│ basic_ios<charT,traits> : ios_base [iostreams.base] │ 状态与格式:
│ rdstate()/exceptions() flags()/width()/precision() │ iostate、fmtflags、
│ fill() tie() getloc() rdbuf() ─────────┐ │ locale、tie
├─────────────────────────────────────────────┼─────────┤
│ basic_streambuf<charT,traits> [stream.buffers] ◀──┘ │ 缓冲与搬运:
│ get 区、put 区 │ underflow/overflow/sync
│ 派生:filebuf / stringbuf / spanbuf / syncbuf │
└───────────────────────────────────────────────────────┘
│
文件 / FILE* / string / span / 另一个 streambuf流缓冲区(stream buffer,basic_streambuf 的派生类)是唯一接触外部的一层:它决定字符从哪里来、到哪里去、什么时候搬运。自定义一个 streambuf,就能让所有现成的 <<、>> 写到网络或压缩文件里,见 [stream.buffers]。
basic_ios 和它的基类 ios_base 只是一组状态:错误状态位、异常掩码、格式标志、宽度、精度、填充字符、locale、tie 指针,以及指向流缓冲区的指针。basic_ios 是 basic_istream 和 basic_ostream 的虚基类,所以同时继承两者的 basic_iostream 里只有一份状态([iostream.objects])。详见 [iostreams.base]。
basic_istream/basic_ostream 负责值和字符之间的转换。数值转换委托给 locale 里的 num_get/num_put facet,它们直接操作流缓冲区([input.streams]、[output.streams])。
所以标准里的"流"有两种对象,读条文时要分清:流对象有状态位,流缓冲区有缓冲指针。cout.flush() 是流对象的成员,它的效果是调用 rdbuf()->pubsync()。
几条贯穿全章的规则#
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("1 2 3\n");
int x, n = 0;
while (!in.eof()) { // 错误的循环条件
in >> x;
++n;
}
std::cout << n << '\n'; // 4:最后一次提取失败了
}读完 3 之后,流停在换行符前面,eofbit 还没有置位,于是循环又执行了一次。这次提取跳过换行、撞到末尾,失败了,x 不变,计数却加了一。
- 状态位一旦置位就保持,直到被清除,而且记录的是已经发生的事:
eofbit表示某次输入撞到了序列末尾,不预言下一次读取。正确的写法是while (in >> x),见 [iostreams.base]。 - 格式标志也一直生效,
std::hex、std::fixed、std::setfill直到被改掉为止。例外是宽度:大多数格式化输出用完它就把它清零([output.streams])。 - 每个输入输出函数先构造一个 sentry 对象(sentry)。它检查流状态、刷新绑定(tie)的输出流,格式化输入时还跳过前导空白。
cin >> x之前cout的提示一定会显示,就是 sentry 刷新了cout。 - 标准流对象默认与 C 的 stdio 同步,
cout和printf的输出可以任意交错。sync_with_stdio(false)放弃这一保证([iostream.objects])。 - 多个线程并发访问同一个流对象或流缓冲区是数据竞争。例外是处于同步状态的标准流对象,以及为此设计的
osyncstream([iostreams.requirements]、[syncstream])。
子条款与头文件(¶1–¶2)#
¶1 第 31 章描述 C++ 程序做输入输出用的组件。¶2 的表 135 列出子条款和对应的头文件:
| 子条款 | 内容 | 头文件 | 本站笔记 |
|---|---|---|---|
| [iostreams.requirements] | 对 charT、traits 的限制,streamoff/streamsize,线程安全 |
[iostreams.requirements] | |
| [iostream.forward] | 所有流类模板的前置声明和别名 | <iosfwd> |
[iostream.objects] |
| [iostream.objects] | cin/cout/cerr/clog 及宽字符版本 |
<iostream> |
[iostream.objects] |
| [iostreams.base] | ios_base、basic_ios、fpos、状态位、格式标志 |
<ios> |
[iostreams.base] |
| [stream.buffers] | basic_streambuf |
<streambuf> |
[stream.buffers] |
| [iostream.format] | 输入输出流、操纵符、print |
<istream>、<ostream>、<iomanip>、<print> |
[iostream.format]、[input.streams]、[output.streams] |
| [string.streams] | 以 basic_string 为存储的流 |
<sstream> |
[string.streams] |
| [span.streams] | 以 span<charT> 为存储的流 C++23 |
<spanstream> |
[span.streams] |
| [file.streams] | 文件流 | <fstream> |
[file.streams] |
| [syncstream] | 多线程下不交错的输出 C++20 | <syncstream> |
[syncstream] |
| [filesystems] | 路径、目录遍历、文件操作 | <filesystem> |
[filesystems] |
| [c.files] | C 的文件函数 | <cstdio>、<cinttypes> |
[c.files] |
几样与流有关的东西不在本章。istream_iterator、istreambuf_iterator 等流迭代器在迭代器一章的 [stream.iterators];std::format 和格式串语法在 [format];locale、num_get/num_put、codecvt 在本地化一章 [localization]。
与 <format>/<print>、<cstdio> 的关系#
C++20 的 std::format 和 C++23 的 std::print 只取代了 iostream 的格式化层,字符的传输仍然走原来的路径:
std::print(FILE*, ...)([print.fun])直接写 C 流;std::print(std::ostream&, ...)([ostream.formatted.print])先用vformat生成字符串,再经由流的 sentry 和流缓冲区写出。流的width、flags不影响结果;流的locale只在格式串使用L选项时起作用。
<cstdio> 的内容与 C 的 <stdio.h> 相同([c.files])。C++ 只补充了三条:把数据交付给宿主环境写入文件的函数调用返回时是一个可观察检查点([intro.compliance]);fscanf 的 %p 读到的值对应多个指针值时,结果在其中未指定地选一个;以空指针调用 tmpnam 可能与其他这样的调用发生数据竞争。
<filesystem>#
[filesystems] 与 iostream 几乎没有交集。它不读写文件内容,只处理路径(path 上的运算都是纯字符串运算)和文件系统中的对象(目录遍历、状态查询、复制、删除)。条文大量以 POSIX 为参照,每个可能失败的操作都有抛异常和接受 error_code& 两套重载,并且规定了文件系统竞争导致未定义行为。从 [filesystems] 开始读。
小结#
| 想了解 | 去读 |
|---|---|
eof/fail/bad 的精确含义、异常掩码、格式标志、xalloc |
[iostreams.base] |
自己写 streambuf:underflow/overflow/sync 的契约 |
[stream.buffers] |
>>、getline、read、ignore、sentry 的逐步行为 |
[input.streams] |
<<、宽度与填充、endl 与刷新、print(ostream&) |
[output.streams] |
setw/setprecision/quoted/put_time、std::print |
[iostream.format] |
cout 什么时候构造、sync_with_stdio |
[iostream.objects] |
多线程写 cout |
[iostreams.requirements]、[syncstream] |
| 内存中的流 | [string.streams]、[span.streams] |
文件流、打开模式、native_handle |
[file.streams] |
| 路径、目录遍历、文件操作 | [filesystems] 及其子页 |
其余条文
¶2 的正文只列举到文件流为止,没有提 span 流、同步流、文件系统和 C 库文件;表 135 是完整的清单。
条款一览
- 31.1General 概述[input.output.general]
- 31.2Iostreams requirements iostream 要求[iostreams.requirements]完成
- 31.3Forward declarations 前置声明[iostream.forward]
- 31.4Standard iostream objects 标准 iostream 对象[iostream.objects]完成
- 31.5Iostreams base classes iostream 基类[iostreams.base]完成
- 31.5.1Header <ios> synopsis 头文件 <ios> 概要[ios.syn]
- 31.5.2Class ios_base 类 ios_base[ios.base]
- 31.5.2.1General 概述[ios.base.general]
- 31.5.2.2Types 类型[ios.types]
- 31.5.2.2.1Class ios_base::failure 类 ios_base::failure[ios.failure]
- 31.5.2.2.2Type ios_base::fmtflags 类型 ios_base::fmtflags[ios.fmtflags]
- 31.5.2.2.3Type ios_base::iostate 类型 ios_base::iostate[ios.iostate]
- 31.5.2.2.4Type ios_base::openmode 类型 ios_base::openmode[ios.openmode]
- 31.5.2.2.5Type ios_base::seekdir 类型 ios_base::seekdir[ios.seekdir]
- 31.5.2.2.6Class ios_base::Init 类 ios_base::Init[ios.init]
- 31.5.2.3State functions 状态函数[fmtflags.state]
- 31.5.2.4Functions 函数[ios.base.locales]
- 31.5.2.5Static members 静态成员[ios.members.static]
- 31.5.2.6Storage functions 存储函数[ios.base.storage]
- 31.5.2.7Callbacks 回调[ios.base.callback]
- 31.5.2.8Constructors and destructor 构造函数与析构函数[ios.base.cons]
- 31.5.3Class template fpos 类模板 fpos[fpos]
- 31.5.4Class template basic_ios 类模板 basic_ios[ios]
- 31.5.5ios_base manipulators ios_base 操纵符[std.ios.manip]
- 31.5.6Error reporting 错误报告[error.reporting]
- 31.6Stream buffers 流缓冲[stream.buffers]完成
- 31.6.1Header <streambuf> synopsis 头文件 <streambuf> 概要[streambuf.syn]
- 31.6.2Stream buffer requirements 流缓冲要求[streambuf.reqts]
- 31.6.3Class template basic_streambuf 类模板 basic_streambuf[streambuf]
- 31.7Formatting and manipulators 格式化与操纵符[iostream.format]完成
- 31.7.1Header <istream> synopsis 头文件 <istream> 概要[istream.syn]
- 31.7.2Header <ostream> synopsis 头文件 <ostream> 概要[ostream.syn]
- 31.7.3Header <iomanip> synopsis 头文件 <iomanip> 概要[iomanip.syn]
- 31.7.4Header <print> synopsis 头文件 <print> 概要[print.syn]
- 31.7.5Input streams 输入流[input.streams]完成
- 31.7.5.1General 概述[input.streams.general]
- 31.7.5.2Class template basic_istream 类模板 basic_istream[istream]
- 31.7.5.3Formatted input functions 有格式输入函数[istream.formatted]
- 31.7.5.4Unformatted input functions 无格式输入函数[istream.unformatted]
- 31.7.5.5Standard basic_istream manipulators 标准 basic_istream 操纵符[istream.manip]
- 31.7.5.6Rvalue stream extraction 右值流提取[istream.rvalue]
- 31.7.5.7Class template basic_iostream 类模板 basic_iostream[iostreamclass]
- 31.7.6Output streams 输出流[output.streams]完成
- 31.7.6.1General 概述[output.streams.general]
- 31.7.6.2Class template basic_ostream 类模板 basic_ostream[ostream]
- 31.7.6.3Formatted output functions 有格式输出函数[ostream.formatted]
- 31.7.6.3.1Common requirements 共同要求[ostream.formatted.reqmts]
- 31.7.6.3.2Arithmetic inserters 算术插入器[ostream.inserters.arithmetic]
- 31.7.6.3.3basic_ostream::operator<< basic_ostream::operator<<[ostream.inserters]
- 31.7.6.3.4Character inserter function templates 字符插入器函数模板[ostream.inserters.character]
- 31.7.6.3.5Print 打印[ostream.formatted.print]
- 31.7.6.4Unformatted output functions 无格式输出函数[ostream.unformatted]
- 31.7.6.5Standard basic_ostream manipulators 标准 basic_ostream 操纵符[ostream.manip]
- 31.7.6.6Rvalue stream insertion 右值流插入[ostream.rvalue]
- 31.7.7Standard manipulators 标准操纵符[std.manip]
- 31.7.8Extended manipulators 扩展操纵符[ext.manip]
- 31.7.9Quoted manipulators 引号操纵符[quoted.manip]
- 31.7.10Print functions 打印函数[print.fun]
- 31.8String-based streams 基于字符串的流[string.streams]完成
- 31.8.1Header <sstream> synopsis 头文件 <sstream> 概要[sstream.syn]
- 31.8.2Class template basic_stringbuf 类模板 basic_stringbuf[stringbuf]
- 31.8.3Class template basic_istringstream 类模板 basic_istringstream[istringstream]
- 31.8.4Class template basic_ostringstream 类模板 basic_ostringstream[ostringstream]
- 31.8.5Class template basic_stringstream 类模板 basic_stringstream[stringstream]
- 31.9Span-based streams 基于 span 的流[span.streams]完成
- 31.9.1Overview 概览[span.streams.overview]
- 31.9.2Header <spanstream> synopsis 头文件 <spanstream> 概要[spanstream.syn]
- 31.9.3Class template basic_spanbuf 类模板 basic_spanbuf[spanbuf]
- 31.9.4Class template basic_ispanstream 类模板 basic_ispanstream[ispanstream]
- 31.9.5Class template basic_ospanstream 类模板 basic_ospanstream[ospanstream]
- 31.9.6Class template basic_spanstream 类模板 basic_spanstream[spanstream]
- 31.10File-based streams 基于文件的流[file.streams]完成
- 31.10.1Header <fstream> synopsis 头文件 <fstream> 概要[fstream.syn]
- 31.10.2Native handles 原生句柄[file.native]
- 31.10.3Class template basic_filebuf 类模板 basic_filebuf[filebuf]
- 31.10.4Class template basic_ifstream 类模板 basic_ifstream[ifstream]
- 31.10.5Class template basic_ofstream 类模板 basic_ofstream[ofstream]
- 31.10.6Class template basic_fstream 类模板 basic_fstream[fstream]
- 31.11Synchronized output streams 同步输出流[syncstream]完成
- 31.11.1Header <syncstream> synopsis 头文件 <syncstream> 概要[syncstream.syn]
- 31.11.2Class template basic_syncbuf 类模板 basic_syncbuf[syncstream.syncbuf]
- 31.11.2.1Overview 概览[syncstream.syncbuf.overview]
- 31.11.2.2Construction and destruction 构造与析构[syncstream.syncbuf.cons]
- 31.11.2.3Assignment and swap 赋值与交换[syncstream.syncbuf.assign]
- 31.11.2.4Member functions 成员函数[syncstream.syncbuf.members]
- 31.11.2.5Overridden virtual functions 覆盖的虚函数[syncstream.syncbuf.virtuals]
- 31.11.2.6Specialized algorithms 特化的算法[syncstream.syncbuf.special]
- 31.11.3Class template basic_osyncstream 类模板 basic_osyncstream[syncstream.osyncstream]
- 31.12File systems 文件系统[filesystems]完成
- 31.12.1General 概述[fs.general]
- 31.12.2Conformance 一致性[fs.conformance]
- 31.12.3Requirements 要求[fs.req]
- 31.12.4Header <filesystem> synopsis 头文件 <filesystem> 概要[fs.filesystem.syn]
- 31.12.5Error reporting 错误报告[fs.err.report]
- 31.12.6Class path 类 path[fs.class.path]完成
- 31.12.6.1General 概述[fs.class.path.general]
- 31.12.6.2Generic pathname format 通用路径名格式[fs.path.generic]
- 31.12.6.3Conversions 转换[fs.path.cvt]
- 31.12.6.4Requirements 要求[fs.path.req]
- 31.12.6.5Members 成员[fs.path.member]
- 31.12.6.5.1Constructors 构造函数[fs.path.construct]
- 31.12.6.5.2Assignments 赋值[fs.path.assign]
- 31.12.6.5.3Appends 追加[fs.path.append]
- 31.12.6.5.4Concatenation 连接[fs.path.concat]
- 31.12.6.5.5Modifiers 修改器[fs.path.modifiers]
- 31.12.6.5.6Native format observers 原生格式观察器[fs.path.native.obs]
- 31.12.6.5.7Generic format observers 通用格式观察器[fs.path.generic.obs]
- 31.12.6.5.8Compare 比较[fs.path.compare]
- 31.12.6.5.9Decomposition 分解[fs.path.decompose]
- 31.12.6.5.10Query 查询[fs.path.query]
- 31.12.6.5.11Generation 生成[fs.path.gen]
- 31.12.6.6Iterators 迭代器[fs.path.itr]
- 31.12.6.7Inserter and extractor 插入器与提取器[fs.path.io]
- 31.12.6.8Non-member functions 非成员函数[fs.path.nonmember]
- 31.12.6.9Formatting support 格式化支持[fs.path.fmtr]
- 31.12.6.10Hash support 散列支持[fs.path.hash]
- 31.12.7Class filesystem_error 类 filesystem_error[fs.class.filesystem.error]
- 31.12.8Enumerations 枚举[fs.enum]
- 31.12.8.1Enum path::format 枚举 path::format[fs.enum.path.format]
- 31.12.8.2Enum class file_type 枚举类 file_type[fs.enum.file.type]
- 31.12.8.3Enum class copy_options 枚举类 copy_options[fs.enum.copy.opts]
- 31.12.8.4Enum class perms 枚举类 perms[fs.enum.perms]
- 31.12.8.5Enum class perm_options 枚举类 perm_options[fs.enum.perm.opts]
- 31.12.8.6Enum class directory_options 枚举类 directory_options[fs.enum.dir.opts]
- 31.12.9Class file_status 类 file_status[fs.class.file.status]
- 31.12.10Class directory_entry 类 directory_entry[fs.class.directory.entry]
- 31.12.11Class directory_iterator 类 directory_iterator[fs.class.directory.iterator]完成
- 31.12.12Class recursive_directory_iterator 类 recursive_directory_iterator[fs.class.rec.dir.itr]
- 31.12.13Filesystem operation functions 文件系统操作函数[fs.op.funcs]完成
- 31.12.13.1General 概述[fs.op.funcs.general]
- 31.12.13.2Absolute absolute[fs.op.absolute]
- 31.12.13.3Canonical canonical[fs.op.canonical]
- 31.12.13.4Copy copy[fs.op.copy]
- 31.12.13.5Copy file copy_file[fs.op.copy.file]
- 31.12.13.6Copy symlink copy_symlink[fs.op.copy.symlink]
- 31.12.13.7Create directories create_directories[fs.op.create.directories]
- 31.12.13.8Create directory create_directory[fs.op.create.directory]
- 31.12.13.9Create directory symlink create_directory_symlink[fs.op.create.dir.symlk]
- 31.12.13.10Create hard link create_hard_link[fs.op.create.hard.lk]
- 31.12.13.11Create symlink create_symlink[fs.op.create.symlink]
- 31.12.13.12Current path current_path[fs.op.current.path]
- 31.12.13.13Equivalent equivalent[fs.op.equivalent]
- 31.12.13.14Exists exists[fs.op.exists]
- 31.12.13.15File size file_size[fs.op.file.size]
- 31.12.13.16Hard link count hard_link_count[fs.op.hard.lk.ct]
- 31.12.13.17Is block file is_block_file[fs.op.is.block.file]
- 31.12.13.18Is character file is_character_file[fs.op.is.char.file]
- 31.12.13.19Is directory is_directory[fs.op.is.directory]
- 31.12.13.20Is empty is_empty[fs.op.is.empty]
- 31.12.13.21Is fifo is_fifo[fs.op.is.fifo]
- 31.12.13.22Is other is_other[fs.op.is.other]
- 31.12.13.23Is regular file is_regular_file[fs.op.is.regular.file]
- 31.12.13.24Is socket is_socket[fs.op.is.socket]
- 31.12.13.25Is symlink is_symlink[fs.op.is.symlink]
- 31.12.13.26Last write time last_write_time[fs.op.last.write.time]
- 31.12.13.27Permissions permissions[fs.op.permissions]
- 31.12.13.28Proximate proximate[fs.op.proximate]
- 31.12.13.29Read symlink read_symlink[fs.op.read.symlink]
- 31.12.13.30Relative relative[fs.op.relative]
- 31.12.13.31Remove remove[fs.op.remove]
- 31.12.13.32Remove all remove_all[fs.op.remove.all]
- 31.12.13.33Rename rename[fs.op.rename]
- 31.12.13.34Resize file resize_file[fs.op.resize.file]
- 31.12.13.35Space space[fs.op.space]
- 31.12.13.36Status status[fs.op.status]
- 31.12.13.37Status known status_known[fs.op.status.known]
- 31.12.13.38Symlink status symlink_status[fs.op.symlink.status]
- 31.12.13.39Temporary directory path temp_directory_path[fs.op.temp.dir.path]
- 31.12.13.40Weakly canonical weakly_canonical[fs.op.weakly.canonical]
- 31.13C library files C 库文件[c.files]完成