Input/output library
A guide to chapter 31: iostreams consist of a state layer, a formatting layer and a buffering layer; what each subclause and header covers; how they relate to <format>/<print>, <cstdio> and <filesystem>.
Key points
- An iostream consists of three layers:
basic_streambufbuffers and transports characters,ios_base/basic_ioshold state and formatting, andbasic_istream/basic_ostreamconvert between values and characters. - Swap the stream buffer, and the same
ostreamwrites to a string, a file or the terminal; the formatting state stays on the stream object. - The state bits record what has already happened.
eofbitmeans some read ran into the end, so a read loop must use the extraction itself as its condition. std::formatandstd::printreplace the formatting layer; characters are still written through a stream buffer or a CFILE*.<filesystem>is in this chapter too, but it deals with paths and directories and does not read or write file contents.
Three layers#
#include <iostream>
#include <sstream>
int main() {
std::stringbuf sb; // buffering layer: characters go into a string
std::ostream out(&sb); // formatting and state layers
out << std::hex << 255;
std::cout << sb.str() << '\n'; // ff
out.rdbuf(std::cout.rdbuf()); // switch to stdout's buffer
out << 255 << '\n'; // ff: hex is still set on out
}out itself does not know where the characters end up. It turns 255 into the hexadecimal characters ff and hands them to the stream buffer it points to. Change the buffer and the destination changes, while the hex format flag stays on out.
A cout << 42 passes through the three layers in turn:
user code: cout << 42; cin >> x;
│ │
┌─────────────────┴────────────────────┴───────────────┐
│ basic_ostream / basic_istream [iostream.format] │ value ↔ chars:
│ operator<< / >>, put/write, get/read/getline │ sentry, num_put/num_get
├───────────────────────────────────────────────────────┤
│ basic_ios<charT,traits> : ios_base [iostreams.base] │ state and format:
│ rdstate()/exceptions() flags()/width()/precision() │ iostate, fmtflags,
│ fill() tie() getloc() rdbuf() ─────────┐ │ locale, tie
├─────────────────────────────────────────────┼─────────┤
│ basic_streambuf<charT,traits> [stream.buffers] ◀──┘ │ buffering/transport:
│ get area, put area │ underflow/overflow/sync
│ derived: filebuf / stringbuf / spanbuf / syncbuf │
└───────────────────────────────────────────────────────┘
│
file / FILE* / string / span / another streambufThe stream buffer (stream buffer, a class derived from basic_streambuf) is the only layer that touches the outside: it decides where characters come from, where they go, and when they are transported. Write your own streambuf, and every existing << and >> can write to a socket or a compressed file; see [stream.buffers].
basic_ios and its base class ios_base are just a bundle of state: the error state bits, the exception mask, the format flags, width, precision, fill character, locale, the tie pointer, and the pointer to the stream buffer. basic_ios is a virtual base class of both basic_istream and basic_ostream, so basic_iostream, which inherits from both, has only one copy of the state ([iostream.objects]). See [iostreams.base].
basic_istream/basic_ostream convert between values and characters. Numeric conversion is delegated to the num_get/num_put facets in the locale, which operate directly on the stream buffer ([input.streams], [output.streams]).
So a "stream" in the standard involves two kinds of objects, and the wording has to be read with that in mind: stream objects have state bits, stream buffers have buffer pointers. cout.flush() is a member of the stream object, and its effect is to call rdbuf()->pubsync().
Rules that run through the chapter#
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("1 2 3\n");
int x, n = 0;
while (!in.eof()) { // wrong loop condition
in >> x;
++n;
}
std::cout << n << '\n'; // 4: the last extraction failed
}After reading 3, the stream stops in front of the newline and eofbit is not yet set, so the loop runs once more. That extraction skips the newline, runs into the end and fails; x is unchanged, but the counter is incremented anyway.
- Once set, a state bit stays set until cleared, and it records what has already happened:
eofbitmeans some input operation ran into the end of the sequence; it does not predict the next read. The correct form iswhile (in >> x); see [iostreams.base]. - Format flags also stay in effect:
std::hex,std::fixedandstd::setfilllast until changed. The exception is width: most formatted output functions reset it to zero after using it ([output.streams]). - Every input and output function first constructs a sentry object (sentry). It checks the stream state, flushes the tied output stream, and for formatted input skips leading whitespace. The prompt written to
coutbeforecin >> xis guaranteed to appear because the sentry flushescout. - The standard stream objects are synchronized with C stdio by default, so output from
coutandprintfcan be freely interleaved.sync_with_stdio(false)gives up this guarantee ([iostream.objects]). - Concurrent access to the same stream object or stream buffer from multiple threads is a data race. The exceptions are the standard stream objects while synchronized, and
osyncstream, which is designed for this ([iostreams.requirements], [syncstream]).
Subclauses and headers (¶1–¶2)#
¶1 Chapter 31 describes the components C++ programs use for input and output. Table 135 in ¶2 lists the subclauses and the corresponding headers:
| Subclause | Contents | Header | Note on this site |
|---|---|---|---|
| [iostreams.requirements] | Restrictions on charT and traits, streamoff/streamsize, thread safety |
[iostreams.requirements] | |
| [iostream.forward] | Forward declarations and aliases for all stream class templates | <iosfwd> |
[iostream.objects] |
| [iostream.objects] | cin/cout/cerr/clog and the wide versions |
<iostream> |
[iostream.objects] |
| [iostreams.base] | ios_base, basic_ios, fpos, state bits, format flags |
<ios> |
[iostreams.base] |
| [stream.buffers] | basic_streambuf |
<streambuf> |
[stream.buffers] |
| [iostream.format] | Input and output streams, manipulators, print |
<istream>, <ostream>, <iomanip>, <print> |
[iostream.format], [input.streams], [output.streams] |
| [string.streams] | Streams backed by a basic_string |
<sstream> |
[string.streams] |
| [span.streams] | Streams backed by a span<charT> C++23 |
<spanstream> |
[span.streams] |
| [file.streams] | File streams | <fstream> |
[file.streams] |
| [syncstream] | Non-interleaved output across threads C++20 | <syncstream> |
[syncstream] |
| [filesystems] | Paths, directory iteration, file operations | <filesystem> |
[filesystems] |
| [c.files] | C file functions | <cstdio>, <cinttypes> |
[c.files] |
A few stream-related things are not in this chapter. Stream iterators such as istream_iterator and istreambuf_iterator are in [stream.iterators] in the iterators chapter; std::format and the format string syntax are in [format]; locale, num_get/num_put and codecvt are in the localization chapter, [localization].
Relation to <format>/<print> and <cstdio>#
C++20's std::format and C++23's std::print replace only the formatting layer of iostreams; characters still travel the old routes:
std::print(FILE*, ...)([print.fun]) writes directly to a C stream;std::print(std::ostream&, ...)([ostream.formatted.print]) first produces a string withvformat, then writes it through the stream's sentry and stream buffer. The stream'swidthandflagsdo not affect the result; the stream'slocalematters only when the format string uses theLoption.
<cstdio> has the same contents as C's <stdio.h> ([c.files]). C++ adds only three things: the return from a function call that delivers data to the host environment to be written to a file is an observable checkpoint ([intro.compliance]); when the value read by fscanf's %p corresponds to more than one pointer value, the result is an unspecified one of them; and calling tmpnam with a null pointer may cause a data race with other such calls.
<filesystem>#
[filesystems] has almost nothing in common with iostreams. It does not read or write file contents; it deals only with paths (operations on path are purely string operations) and with objects in the file system (directory iteration, status queries, copying, removal). The wording leans heavily on POSIX, every operation that can fail has two overloads, one throwing and one taking an error_code&, and file system races are specified to cause undefined behavior. Start reading at [filesystems].
Summary#
| To learn about | Read |
|---|---|
The exact meaning of eof/fail/bad, the exception mask, format flags, xalloc |
[iostreams.base] |
Writing your own streambuf: the contracts of underflow/overflow/sync |
[stream.buffers] |
Step-by-step behavior of >>, getline, read, ignore, the sentry |
[input.streams] |
<<, width and fill, endl and flushing, print(ostream&) |
[output.streams] |
setw/setprecision/quoted/put_time, std::print |
[iostream.format] |
When cout is constructed, sync_with_stdio |
[iostream.objects] |
Writing to cout from multiple threads |
[iostreams.requirements], [syncstream] |
| In-memory streams | [string.streams], [span.streams] |
File streams, open modes, native_handle |
[file.streams] |
| Paths, directory iteration, file operations | [filesystems] and its subpages |
Remaining wording
The body text of ¶2 lists only up to file streams; it does not mention span streams, synchronized streams, file systems or the C library files. Table 135 is the complete list.
Contents
- 31.1General[input.output.general]
- 31.2Iostreams requirements[iostreams.requirements]done
- 31.3Forward declarations[iostream.forward]
- 31.4Standard iostream objects[iostream.objects]done
- 31.5Iostreams base classes[iostreams.base]done
- 31.5.1Header <ios> synopsis[ios.syn]
- 31.5.2Class ios_base[ios.base]
- 31.5.2.1General[ios.base.general]
- 31.5.2.2Types[ios.types]
- 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]
- 31.5.4Class template basic_ios[ios]
- 31.5.5ios_base manipulators[std.ios.manip]
- 31.5.6Error reporting[error.reporting]
- 31.6Stream buffers[stream.buffers]done
- 31.6.1Header <streambuf> synopsis[streambuf.syn]
- 31.6.2Stream buffer requirements[streambuf.reqts]
- 31.6.3Class template basic_streambuf[streambuf]
- 31.7Formatting and manipulators[iostream.format]done
- 31.7.1Header <istream> synopsis[istream.syn]
- 31.7.2Header <ostream> synopsis[ostream.syn]
- 31.7.3Header <iomanip> synopsis[iomanip.syn]
- 31.7.4Header <print> synopsis[print.syn]
- 31.7.5Input streams[input.streams]done
- 31.7.5.1General[input.streams.general]
- 31.7.5.2Class template 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[istream.manip]
- 31.7.5.6Rvalue stream extraction[istream.rvalue]
- 31.7.5.7Class template basic_iostream[iostreamclass]
- 31.7.6Output streams[output.streams]done
- 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]done
- 31.9Span-based streams[span.streams]done
- 31.10File-based streams[file.streams]done
- 31.11Synchronized output streams[syncstream]done
- 31.11.1Header <syncstream> synopsis[syncstream.syn]
- 31.11.2Class template 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[syncstream.osyncstream]
- 31.12File systems[filesystems]done
- 31.12.1General[fs.general]
- 31.12.2Conformance[fs.conformance]
- 31.12.3Requirements[fs.req]
- 31.12.4Header <filesystem> synopsis[fs.filesystem.syn]
- 31.12.5Error reporting[fs.err.report]
- 31.12.6Class path[fs.class.path]done
- 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[fs.class.filesystem.error]
- 31.12.8Enumerations[fs.enum]
- 31.12.9Class file_status[fs.class.file.status]
- 31.12.10Class directory_entry[fs.class.directory.entry]
- 31.12.11Class directory_iterator[fs.class.directory.iterator]done
- 31.12.12Class recursive_directory_iterator[fs.class.rec.dir.itr]
- 31.12.13Filesystem operation functions[fs.op.funcs]done
- 31.12.13.1General[fs.op.funcs.general]
- 31.12.13.2Absolute[fs.op.absolute]
- 31.12.13.3Canonical[fs.op.canonical]
- 31.12.13.4Copy[fs.op.copy]
- 31.12.13.5Copy file[fs.op.copy.file]
- 31.12.13.6Copy symlink[fs.op.copy.symlink]
- 31.12.13.7Create directories[fs.op.create.directories]
- 31.12.13.8Create directory[fs.op.create.directory]
- 31.12.13.9Create directory symlink[fs.op.create.dir.symlk]
- 31.12.13.10Create hard link[fs.op.create.hard.lk]
- 31.12.13.11Create symlink[fs.op.create.symlink]
- 31.12.13.12Current path[fs.op.current.path]
- 31.12.13.13Equivalent[fs.op.equivalent]
- 31.12.13.14Exists[fs.op.exists]
- 31.12.13.15File size[fs.op.file.size]
- 31.12.13.16Hard link count[fs.op.hard.lk.ct]
- 31.12.13.17Is block file[fs.op.is.block.file]
- 31.12.13.18Is character file[fs.op.is.char.file]
- 31.12.13.19Is directory[fs.op.is.directory]
- 31.12.13.20Is empty[fs.op.is.empty]
- 31.12.13.21Is fifo[fs.op.is.fifo]
- 31.12.13.22Is other[fs.op.is.other]
- 31.12.13.23Is regular file[fs.op.is.regular.file]
- 31.12.13.24Is socket[fs.op.is.socket]
- 31.12.13.25Is symlink[fs.op.is.symlink]
- 31.12.13.26Last write time[fs.op.last.write.time]
- 31.12.13.27Permissions[fs.op.permissions]
- 31.12.13.28Proximate[fs.op.proximate]
- 31.12.13.29Read symlink[fs.op.read.symlink]
- 31.12.13.30Relative[fs.op.relative]
- 31.12.13.31Remove[fs.op.remove]
- 31.12.13.32Remove all[fs.op.remove.all]
- 31.12.13.33Rename[fs.op.rename]
- 31.12.13.34Resize file[fs.op.resize.file]
- 31.12.13.35Space[fs.op.space]
- 31.12.13.36Status[fs.op.status]
- 31.12.13.37Status known[fs.op.status.known]
- 31.12.13.38Symlink status[fs.op.symlink.status]
- 31.12.13.39Temporary directory path[fs.op.temp.dir.path]
- 31.12.13.40Weakly canonical[fs.op.weakly.canonical]
- 31.13C library files[c.files]done