The IO Library#
Summary based on C++ Primer, 5th ed. Chapter 8 (The IO Library).
1. IO Library Headers and Inheritance Hierarchy#
The C++ IO library is organized into three main headers handling console, file, and in-memory string streams, sharing a unified interface through inheritance.
| Header | Core Types / Objects | Base Class (>>, <<, getline Inherited) | Type-Specific Member Functions | Role |
|---|---|---|---|---|
<iostream> | Types: istream, ostream, iostreamGlobal Objects: cin, cout, cerr (unbuffered), clog (buffered) | Root stream base classes | - | Console (standard I/O) streams |
<fstream> | ifstream, ofstream, fstream | Inherits from istream, ostream, iostream | .open(), .close(), .is_open() | File I/O streams |
<sstream> | istringstream, ostringstream, stringstream | Inherits from istream, ostream, iostream | .str(), .str(S) | In-memory std::string streams |
Benefit of Polymorphism: Because
ifstreamandistringstreamboth inherit fromstd::istream, any function taking astd::istream&reference (e.g.,read(std::istream&, Sales_data&)) works seamlessly withstd::cin, file streams (ifstream), and string streams (istringstream) without modification.
2. No Copy or Assignment for IO Objects#
IO stream objects cannot be copied or assigned; their copy constructors and copy-assignment operators are deleted (= delete) so that two stream objects cannot concurrently mutate the same underlying buffer state.
std::ofstream out1, out2;
// out1 = out2; // Compile error: cannot assign stream objects
// std::ofstream print(std::ofstream); // Compile error: cannot copy stream objects
- Must Pass and Return by Reference (
&): Functions that take or return IO streams must always use references (std::istream&,std::ostream&). - Cannot Be
constReferences: Reading or writing a stream mutates its internal state (buffer cursor, condition flags), so stream parameters and return types cannot beconst.
3. Stream Condition States#
When an IO error or EOF occurs, the stream sets internal state bits (std::iostate). Once any error bit is set, all subsequent IO operations on that stream fail until the state is explicitly reset via clear().
1. The Four Condition State Bits (Bitmask) and Query Member Functions#
A stream’s condition state (std::iostate) is a bitmask where each flag occupies an independent bit position, meaning multiple bits can be turned on simultaneously (e.g., eofbit | failbit).
| State Bit Constant | Example Bits | Stream Member Function | Description |
|---|---|---|---|
std::ios::goodbit | 000 (0) | .good() | Returns true only if all error/EOF bits are 0 (stream is completely clean) |
std::ios::badbit | 001 (1) | .bad() | Returns true on unrecoverable system/hardware-level IO failure |
std::ios::eofbit | 010 (2) | .eof() | Set when End-of-File is reached; .eof() returns true |
std::ios::failbit | 100 (4) | .fail() | Set when value extraction/conversion fails (e.g., reading "abc" into an int, or failing to read because of EOF). .fail() returns true if either failbit or badbit is set |
- Scenario: repeating
is >> numon"10 20"- First
is >> num(reads10): Succeeds normally → state bits000(goodbit). - Second
is >> num(reads20with no trailing space): Hits the end of the string while reading'2'and'0', but extracting20intonumsucceeded, so onlyeofbitis set → state bits010(eofbit). - Third
is >> num(attempted when no characters remain): Hits EOF and fails to extract a value intonum, so botheofbitandfailbitare set simultaneously → state bits110(eofbit | failbit).
- First
- Stream Evaluation in Conditions (
while (STRM >> word)): The>>operator returns a reference to its LHSSTRM, which converts toboolin a condition by evaluating!STRM.fail(). The loop terminates at Step 3 oncefailbitturns on.
2. Querying and Controlling Condition States (rdstate, clear, setstate)#
| Member Function | Behavior |
|---|---|
.rdstate() | Reads and returns the stream’s current std::iostate bitmask value. |
.clear() | Clears all error bits to 0, restoring the stream to a valid goodbit state. |
.clear(FLAGS) | Overwrites the stream’s condition state with FLAGS. Use STRM.clear(STRM.rdstate() & ~STRM.failbit); to clear only failbit while preserving other bits. |
.setstate(FLAGS) | Preserves existing state bits and turns on the given FLAGS bits. Equivalent to STRM.clear(STRM.rdstate() | FLAGS). |
int val;
std::cin >> val; // If the user types "abc", failbit is set
if (std::cin.fail()) {
// 1. rdstate(): Read and save current stream condition state bits
auto old_state = std::cin.rdstate();
// 2. clear(): Clear all error bits and restore stream to goodbit state
std::cin.clear();
// Optionally discard invalid characters from the buffer and continue
// 3. setstate(FLAGS): Turn on old_state bits in addition to current state
std::cin.setstate(old_state);
}3. Input Loop Patterns: while (is >> num) vs. while (!is.eof())#
| Pattern | Behavior & When to Use |
|---|---|
while (is >> num)Standard Idiom | The default pattern for almost all C++ input loops.
|
while (!is.eof()) + clear()Error-Recovery Only | Used only when you must recover from invalid tokens mid-stream and continue reading until EOF.
|
// 1. Standard input loop: terminates immediately on EOF or format error
while (is >> num) {
out.push_back(num);
}
// 2. Error-recovery loop: skips invalid non-numeric tokens and continues until EOF
while (!is.eof()) {
if (is >> num) {
out.push_back(num);
} else if (is.fail() && !is.eof()) {
is.clear(); // 1. Must clear failbit first so the stream accepts operations again
std::string dummy;
is >> dummy; // 2. Consume and discard the invalid token
}
}4. Managing the Output Buffer#
Output streams buffer data in memory before flushing it to the underlying OS device or file to minimize system call (write) overhead.
1. Five Conditions That Cause a Buffer Flush#
- Normal Program Termination: All output buffers are flushed when
main()returns normally.- Warning: If the program crashes abnormally (
abort, segmentation fault, unhandled exception), data still sitting in the output buffer is NOT flushed and is lost.
- Warning: If the program crashes abnormally (
- Buffer Full: The buffer is automatically flushed when it reaches capacity before writing the next value.
- Explicit Manipulator Functions:
std::cout << "hi!" << std::endl;: Writes a newline (\n) and flushes the buffer.std::cout << "hi!" << std::flush;: Flushes the buffer without adding any characters.std::cout << "hi!" << std::ends;: Writes a null character (\0) and flushes the buffer.
std::unitbufManipulator Function:- Like
std::endl,std::unitbufandstd::nounitbufare I/O manipulator functions passed to<<. - Executing
std::cout << std::unitbuf;sets the stream’s internal format flag to flush after every<<output operation (std::cerrhasunitbufenabled by default;std::cout << std::nounitbuf;restores normal buffering).
- Like
- Tied Streams (
tie):- By default,
std::cinandstd::cerrare tied tostd::cout. - Reading from
std::cin >> x;or writing tostd::cerr << ...automatically flushesstd::coutfirst, ensuring interactive prompts appear on screen before waiting for input.
- By default,
// Inspecting or modifying stream ties
std::ostream *prev_tied = std::cin.tie(nullptr); // Untie cin from cout
std::cin.tie(&std::cout); // Re-tie cin to cout
5. File Input and Output (<fstream>)#
1. Opening, Closing, and RAII Automatic Destruction#
ifstream, ofstream, and fstream objects can open a file directly upon construction by passing the filename to the constructor, or be default-constructed first and opened later by calling their .open() member function (which internally invokes the OS open() system call).
{
// Method 1: Open file directly in the constructor
std::ifstream input("data.txt");
// Method 2: Default-construct first, then call the stream's .open() member function
std::ofstream output;
output.open("result.txt");
if (input.is_open()) { // Or check via if (input)
// Read from file
}
} // When 'input' and 'output' leave their block scope, their destructors automatically call close()
- RAII Automatic
close(): Just as smart pointers (shared_ptr/unique_ptr) automatically calldeletein their destructor,fstreamobjects automatically callclose()in their destructor when leaving scope (RAII). (You only need to callinput.close()explicitly when reusing the same stream variable to open another file viainput.open("other.txt").)
2. File Modes vs. Linux open() Flags#
C++ <fstream> file modes map directly to Linux/POSIX open() system call flags (see File I/O).
C++ File Mode (std::ios::) | Equivalent POSIX open() Flags | Behavior |
|---|---|---|
in (ifstream default) | O_RDONLY | Open for reading only |
out | trunc (ofstream default) | O_WRONLY | O_CREAT | O_TRUNC | Open for writing; creates the file if missing and truncates existing file contents to 0 bytes |
out | app | O_WRONLY | O_CREAT | O_APPEND | Preserves existing contents and appends every write to the end of the file |
in | out (fstream default) | O_RDWR | Open for both reading and writing without truncating existing contents |
ate (At End) | open() followed by lseek(fd, 0, SEEK_END) | Seeks to the end of the file immediately upon opening (unlike app, subsequent writes can seek elsewhere) |
binary | No distinction in POSIX | Perform byte-stream I/O without newline translation |
Critical Pitfall with
std::ofstream: Openingstd::ofstream out("log.txt");without specifying a mode defaults tostd::ios::out | std::ios::trunc(O_TRUNC), immediately wiping out any existing contents inlog.txt. To preserve existing data and append to the file, always specifystd::ios::app.
// 1. Default mode (out | trunc): Wipes existing contents of log.txt to 0 bytes!
std::ofstream out1("log.txt");
// 2. Append mode (out | app): Preserves existing contents and appends at the end
std::ofstream out2("log.txt", std::ios::app);6. In-Memory String Streams (<sstream>)#
<sstream> allows in-memory std::string objects to be read and written using the same stream operators as files or console streams.
1. Parsing with istringstream and Formatting with ostringstream#
std::istringstream: Commonly used to read an entire line viastd::getlineand then parse individual whitespace-delimited words or numbers from that line.std::ostringstream: Commonly used to incrementally format and assemble values of various types in a memory buffer before extracting the finalstd::stringvia.str().
#include <sstream>
#include <string>
#include <vector>
struct PersonInfo {
std::string name;
std::vector<std::string> phones;
};
// 1. istringstream: Parse a name and multiple phone numbers from a single line
PersonInfo parseLine(const std::string &line) {
PersonInfo info;
std::istringstream record(line); // Bind input string stream to a copy of line
record >> info.name; // Extract first whitespace-delimited token
std::string phone;
while (record >> phone) { // Extract remaining tokens until EOF
info.phones.push_back(phone);
}
return info;
}
// 2. ostringstream: Assemble formatted output in memory and extract via str()
std::string formatSummary(const PersonInfo &info) {
std::ostringstream formatted;
formatted << info.name << " (" << info.phones.size() << " numbers)";
return formatted.str(); // Return the assembled std::string
}2. Reusing stringstream Objects: .str("") vs. .clear()#
When declaring a single istringstream or ostringstream outside a loop and reusing it across iterations, calling .clear() alone does NOT empty the underlying string buffer, unlike vector::clear() or string::clear().
| Member Function | Actual Behavior | Does It Clear the String Buffer? |
|---|---|---|
.clear() | Resets only the stream’s error condition state bits (eofbit, failbit, badbit) to goodbit. | ❌ No |
.str() | Returns a std::string copy of the current buffer contents. | ❌ Unchanged |
.str(S) | Replaces the internal string buffer with string S. Pass .str("") to empty the buffer. | ✅ Replaced with S |
// 1. Reusing an input string stream (istringstream) declared outside a loop
std::istringstream record;
std::string line;
while (std::getline(std::cin, line)) {
record.str(line); // 1. Replace the internal buffer with the new line
record.clear(); // 2. Required: Clear eofbit/failbit set when the previous line hit EOF
std::string word;
while (record >> word) { /* ... */ }
}
// 2. Reusing an output string stream (ostringstream) declared outside a loop
std::ostringstream oss;
for (int i = 0; i < 3; ++i) {
oss.str(""); // 1. Empty the internal string buffer (oss.clear() alone will NOT clear text)
oss.clear(); // 2. Reset stream condition state bits
oss << "Item " << i;
std::cout << oss.str() << "\n";
}