Skip to main content

Lesson 3 of 5

File I/O - fstream & std::filesystem

`std::fstream` (and `std::ifstream`/`std::ofstream`) provide C++-style file I/O with RAII - the file is closed when the stream goes out of scope. `std::filesystem` (C++17) provides a portable API for: path manipulation, directory iteration, file metadata (size, modification time), creating/removing directories, and checking file existence - replacing platform-specific `stat()`, `opendir()`, etc.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

ifstream/ofstream, Error Checking & std::filesystem

ifstream/ofstream, Error Checking & std::filesystem
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <stdexcept>
#include <filesystem>  // C++17
#include <iomanip>

namespace fs = std::filesystem;

// ── Text file read ─────────────────────────────────────────────
std::vector<std::string> read_lines(const fs::path& path) {
    std::ifstream file(path);                         // RAII open
    if (!file.is_open()) {
        throw std::runtime_error("Cannot open: " + path.string());
    }
    std::vector<std::string> lines;
    std::string line;
    while (std::getline(file, line)) {               // reads until EOF
        lines.push_back(std::move(line));
    }
    if (file.bad()) {
        throw std::runtime_error("Read error on: " + path.string());
    }
    return lines;  // file closed here (destructor)
}

// ── Text file write ────────────────────────────────────────────
void write_lines(const fs::path& path, const std::vector<std::string>& lines) {
    std::ofstream file(path);                         // creates/truncates
    if (!file) throw std::runtime_error("Cannot write: " + path.string());
    for (const auto& line : lines) {
        file << line << "
";
        if (!file) throw std::runtime_error("Write error");  // disk full etc.
    }
    // flush + close automatic (RAII)
}

// ── Binary file I/O ────────────────────────────────────────────
void write_binary(const fs::path& path, const std::vector<int>& data) {
    std::ofstream f(path, std::ios::binary);
    size_t n = data.size();
    f.write(reinterpret_cast<const char*>(&n), sizeof(n));
    f.write(reinterpret_cast<const char*>(data.data()), n * sizeof(int));
}

std::vector<int> read_binary(const fs::path& path) {
    std::ifstream f(path, std::ios::binary);
    if (!f) throw std::runtime_error("Cannot open binary file");
    size_t n;
    f.read(reinterpret_cast<char*>(&n), sizeof(n));
    std::vector<int> data(n);
    f.read(reinterpret_cast<char*>(data.data()), n * sizeof(int));
    return data;
}

// ── std::filesystem operations ────────────────────────────────
void filesystem_demo() {
    fs::path p = "test_dir";

    if (!fs::exists(p)) {
        fs::create_directory(p);
        std::cout << "Created: " << p << "
";
    }

    // Write a file inside
    write_lines(p / "hello.txt", {"Hello,", "World!", "From C++17"});
    write_lines(p / "data.txt",  {"a 1", "b 2", "c 3"});

    // Directory iteration
    std::cout << "Contents of " << p << ":
";
    for (const auto& entry : fs::directory_iterator(p)) {
        auto sz = fs::file_size(entry.path());
        auto mt = fs::last_write_time(entry.path());
        std::cout << "  " << std::setw(15) << entry.path().filename().string()
                  << "  " << sz << " bytes
";
    }

    // Path operations
    fs::path full = p / "hello.txt";
    std::cout << "stem: "      << full.stem()      << "
";  // hello
    std::cout << "extension: " << full.extension() << "
";   // .txt
    std::cout << "parent: "    << full.parent_path()<< "
"; // test_dir

    // Copy and remove
    fs::copy(p / "hello.txt", p / "hello_copy.txt");
    fs::remove(p / "hello_copy.txt");

    // Read back
    auto lines = read_lines(p / "hello.txt");
    for (const auto& l : lines) std::cout << l << "
";

    // Cleanup
    fs::remove_all(p);  // removes directory and all contents
    std::cout << "Cleaned up " << p << "
";
}

int main() {
    // Binary I/O
    const fs::path bin = "test.bin";
    write_binary(bin, {10, 20, 30, 40, 50});
    auto data = read_binary(bin);
    for (int v : data) std::cout << v << " ";
    std::cout << "
";
    fs::remove(bin);

    // Filesystem demo
    filesystem_demo();
    return 0;
}

Common Mistakes

  • `if (!file)` vs `if (!file.is_open())` - `if (!file)` checks `failbit` OR `badbit` OR `eofbit`. After `getline` at EOF, `failbit` is set even if you read every line successfully. Check `file.bad()` for actual I/O errors, not `file.fail()` which triggers on EOF too.
  • Not flushing before checking success - `file << data` buffers writes. The write may appear to succeed even if the disk is full until the flush. Check `file.flush()` or the stream state after closing or explicitly flushing.
  • `std::filesystem::path` from string literals - `fs::path p = "C:\\Users\\.."` on Windows uses backslash. Use `/` (forward slash) in path literals - `fs::path` handles conversion. Or use raw string literals: `R"(C:\Users\...)"`

Tip

Tip

Practice File IO fstream stdfilesystem in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Stream buffers, file modes, and cross-platform filesystem path manipulation

Practice Task

Note

Practice Task - (1) Write a working example of File IO fstream stdfilesystem from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with File IO fstream stdfilesystem is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • `std::fstream` (and `std::ifstream`/`std::ofstream`) provide C++-style file I/O with RAII - the file is closed when the stream goes out of scope.
  • `if (!file)` vs `if (!file.is_open())` - `if (!file)` checks `failbit` OR `badbit` OR `eofbit`. After `getline` at EOF, `failbit` is set even if you read every line successfully. Check `file.bad()` for actual I/O errors, not `file.fail()` which triggers on EOF too.
  • Not flushing before checking success - `file << data` buffers writes. The write may appear to succeed even if the disk is full until the flush. Check `file.flush()` or the stream state after closing or explicitly flushing.
  • `std::filesystem::path` from string literals - `fs::path p = "C:\\Users\\.."` on Windows uses backslash. Use `/` (forward slash) in path literals - `fs::path` handles conversion. Or use raw string literals: `R"(C:\Users\...)"`

Topics in This Module

0/5 done