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.

HeaderCore Types / ObjectsBase Class (>>, <<, getline Inherited)Type-Specific Member FunctionsRole
<iostream>Types: istream, ostream, iostream
Global Objects: cin, cout, cerr (unbuffered), clog (buffered)
Root stream base classes-Console (standard I/O) streams
<fstream>ifstream, ofstream, fstreamInherits from istream, ostream, iostream.open(), .close(), .is_open()File I/O streams
<sstream>istringstream, ostringstream, stringstreamInherits from istream, ostream, iostream.str(), .str(S)In-memory std::string streams

Benefit of Polymorphism: Because ifstream and istringstream both inherit from std::istream, any function taking a std::istream& reference (e.g., read(std::istream&, Sales_data&)) works seamlessly with std::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 const References: Reading or writing a stream mutates its internal state (buffer cursor, condition flags), so stream parameters and return types cannot be const.

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 ConstantExample BitsStream Member FunctionDescription
std::ios::goodbit000 (0).good()Returns true only if all error/EOF bits are 0 (stream is completely clean)
std::ios::badbit001 (1).bad()Returns true on unrecoverable system/hardware-level IO failure
std::ios::eofbit010 (2).eof()Set when End-of-File is reached; .eof() returns true
std::ios::failbit100 (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 >> num on "10 20"
    1. First is >> num (reads 10): Succeeds normally → state bits 000 (goodbit).
    2. Second is >> num (reads 20 with no trailing space): Hits the end of the string while reading '2' and '0', but extracting 20 into num succeeded, so only eofbit is set → state bits 010 (eofbit).
    3. Third is >> num (attempted when no characters remain): Hits EOF and fails to extract a value into num, so both eofbit and failbit are set simultaneously → state bits 110 (eofbit | failbit).
  • Stream Evaluation in Conditions (while (STRM >> word)): The >> operator returns a reference to its LHS STRM, which converts to bool in a condition by evaluating !STRM.fail(). The loop terminates at Step 3 once failbit turns on.

2. Querying and Controlling Condition States (rdstate, clear, setstate)#

Member FunctionBehavior
.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())#

PatternBehavior & When to Use
while (is >> num)
Standard Idiom
The default pattern for almost all C++ input loops.
  • Attempts the read operation (is >> num or std::getline(is, line)) first and enters the loop body only if the read succeeded (!is.fail()).
  • Safely terminates the loop immediately upon reaching EOF or encountering a format error (failbit).
while (!is.eof()) + clear()
Error-Recovery Only
Used only when you must recover from invalid tokens mid-stream and continue reading until EOF.
  • Examples: Prompting a user to re-enter invalid console input (std::cin), or salvaging valid numbers from a stream containing corrupted tokens.
  • Warning: Writing a naive while (!is.eof()) { is >> num; } without checking if (is >> num) and recovering via is.clear() causes duplicate last-element bugs when trailing whitespace precedes EOF, or infinite loops on failbit.
// 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#

  1. 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.
  2. Buffer Full: The buffer is automatically flushed when it reaches capacity before writing the next value.
  3. 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.
  4. std::unitbuf Manipulator Function:
    • Like std::endl, std::unitbuf and std::nounitbuf are 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::cerr has unitbuf enabled by default; std::cout << std::nounitbuf; restores normal buffering).
  5. Tied Streams (tie):
    • By default, std::cin and std::cerr are tied to std::cout.
    • Reading from std::cin >> x; or writing to std::cerr << ... automatically flushes std::cout first, ensuring interactive prompts appear on screen before waiting for input.
// 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 call delete in their destructor, fstream objects automatically call close() in their destructor when leaving scope (RAII). (You only need to call input.close() explicitly when reusing the same stream variable to open another file via input.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() FlagsBehavior
in (ifstream default)O_RDONLYOpen for reading only
out | trunc (ofstream default)O_WRONLY | O_CREAT | O_TRUNCOpen for writing; creates the file if missing and truncates existing file contents to 0 bytes
out | appO_WRONLY | O_CREAT | O_APPENDPreserves existing contents and appends every write to the end of the file
in | out (fstream default)O_RDWROpen 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)
binaryNo distinction in POSIXPerform byte-stream I/O without newline translation

Critical Pitfall with std::ofstream: Opening std::ofstream out("log.txt"); without specifying a mode defaults to std::ios::out | std::ios::trunc (O_TRUNC), immediately wiping out any existing contents in log.txt. To preserve existing data and append to the file, always specify std::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 via std::getline and 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 final std::string via .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 FunctionActual BehaviorDoes 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";
}