C++ · Module 16 · Lesson 41 min read

std::filesystem (C++17)

Getting started (<filesystem>)

arduino
#include <filesystem>
namespace fs = std::filesystem;

fs::path — portable paths ✅

less
fs::path p = "data";
p /= "reports";                 // data/reports  (or data\reports on Windows)
p / "nov.csv"                   // join with /
p.filename()                    // "nov.csv"
p.stem()                        // "nov"
p.extension()                   // ".csv"
p.parent_path()                 // "data/reports"
p.replace_extension(".txt")

Querying

fs::exists(p), fs::is_directory(p), fs::is_regular_file(p), fs::file_size(p), fs::last_write_time(p), fs::current_path(), fs::absolute(p), fs::temp_directory_path()

Modifying

FunctionDoes
fs::create_directory(p) / create_directories(p)make one / all missing folders
fs::copy_file(a, b, fs::copy_options::overwrite_existing)copy
fs::rename(a, b)move/rename
fs::remove(p)delete a file or empty folder
fs::remove_all(p)delete recursively ⚠️
fs::resize_file, fs::permissions

Listing directories

less
for (const auto& entry : fs::directory_iterator(dir)) { entry.path(), entry.is_regular_file(), entry.file_size() }
for (const auto& entry : fs::recursive_directory_iterator(dir)) { ... }   // includes sub-folders

The order of entries is not guaranteed — sort if you need a stable order.

Errors

Functions throw fs::filesystem_error on failure — or pass a std::error_code& as the last argument for a non-throwing version:

c
std::error_code ec;
fs::remove("x.txt", ec);
if (ec) std::cout << ec.message();

Typical tasks

Backups with timestamps, finding all .csv files, cleaning old logs, computing a folder's total size, making sure an output folder exists before writing.

Example

C++
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

namespace fs = std::filesystem;

int main() {
    fs::path root = "budget_data";
    fs::remove_all(root);                                   // start clean for this demo
    fs::create_directories(root / "reports" / "2026");      // creates every missing folder

    for (const char* name : { "nov.csv", "oct.csv", "notes.txt" }) {
        std::ofstream(root / "reports" / "2026" / name) << "sample content for " << name << '\n';
    }
    std::ofstream(root / "settings.json") << "{ \"currency\": \"NPR\" }\n";

    fs::path report = root / "reports" / "2026" / "nov.csv";
    std::cout << "filename: " << report.filename().string() << ", stem: " << report.stem().string()
              << ", extension: " << report.extension().string() << '\n';
    std::cout << "parent: " << report.parent_path().generic_string() << '\n';
    std::cout << std::boolalpha << "exists? " << fs::exists(report) << ", is directory? " << fs::is_directory(report)
              << ", size: " << fs::file_size(report) << " bytes\n";

    std::vector<std::string> csvs;
    std::uintmax_t total = 0;
    for (const auto& entry : fs::recursive_directory_iterator(root)) {
        if (!entry.is_regular_file()) continue;
        total += entry.file_size();
        if (entry.path().extension() == ".csv") csvs.push_back(entry.path().filename().string());
    }
    std::sort(csvs.begin(), csvs.end());                    // directory order isn't guaranteed
    std::cout << "csv files:";
    for (const auto& c : csvs) std::cout << ' ' << c;
    std::cout << "\ntotal size of all files: " << total << " bytes\n";

    fs::copy_file(report, root / "nov_backup.csv", fs::copy_options::overwrite_existing);
    fs::rename(root / "nov_backup.csv", root / "nov_backup_2026.csv");
    std::cout << "backup exists? " << fs::exists(root / "nov_backup_2026.csv") << '\n';

    std::error_code ec;
    fs::remove(root / "does_not_exist" / "x.txt", ec);      // non-throwing version
    std::cout << "removing a missing file reported an error? " << static_cast<bool>(ec) << '\n';
    try {
        auto size = fs::file_size(root / "missing.txt");
        std::cout << size << '\n';
    } catch (const fs::filesystem_error&) {
        std::cout << "file_size on a missing file threw filesystem_error\n";
    }

    std::cout << "removed " << fs::remove_all(root) << " files and folders\n";
    return 0;
}

/* Output:
filename: nov.csv, stem: nov, extension: .csv
parent: budget_data/reports/2026
exists? true, is directory? false, size: 27 bytes
csv files: nov.csv oct.csv
total size of all files: 105 bytes
backup exists? true
removing a missing file reported an error? false
file_size on a missing file threw filesystem_error
removed 8 files and folders
*/