Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # 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 | | :--- | :--- | :--- | :--- | :--- | | **``** | **Types:** `istream`, `ostream`, `iostream`
**Global Objects:** `cin`, `cout`, `cerr` (unbuffered), `clog` (buffered) | Root stream base classes | - | Console (standard I/O) streams | | **``** | `ifstream`, `ofstream`, `fstream` | Inherits from `istream`, `ostream`, `iostream` | `.open()`, `.close()`, `.is_open()` | File I/O streams | | **``** | `istringstream`, `ostringstream`, `stringstream` | Inherits 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. ```cpp 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 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 >> 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 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)`. | ```cpp 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.**
  • 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`.
| ```cpp // 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. ```cpp // 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 (``) ### 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). ```cpp { // 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]({{< relref "/programming/cpp/raii.md" >}}))**. (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++ `` file modes map directly to Linux/POSIX `open()` system call flags (see [File I/O]({{< relref "/linux/system-programming/file-io.md" >}})). | 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`:** > 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`. ```cpp // 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 (``) `` 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()`. ```cpp #include #include #include struct PersonInfo { std::string name; std::vector 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` | ```cpp // 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"; } ```