Skip to content

std::filesystem (C++17)

TL;DR

A platform-agnostic file system library: path concatenation and normalization, directory creation and traversal, file copying and deletion, permissions and status queries—say goodbye to std::ifstream/std::ofstream and OS APIs.

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

Core API Cheat Sheet

OperationSignatureDescription
Path classstd::filesystem::pathPath construction, concatenation, decomposition (handles cross-platform separators)
Path concatenationp / "subdir"Joins paths with OS-specific separator
Current pathfs::current_pathGets/sets the working directory
Directory iterationfs::directory_iteratorIterates over a single-level directory
Recursive iterationfs::recursive_directory_iteratorRecursively iterates over subdirectories
File statusfs::existsChecks if a path exists
File sizefs::file_sizeGets file size in bytes
Create directoryfs::create_directoryCreates a single directory
Create multi-level directoryfs::create_directoriesRecursively creates the entire path
Copy filefs::copy_fileCopies a single file
Deletefs::removeDeletes a file or empty directory
Recursive deletefs::remove_allRecursively deletes a directory and its contents
Renamefs::renameRenames or moves a file

Minimal Example

cpp
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    // Create directories
    fs::create_directories("sandbox/dir1/dir2");

    // Copy file
    fs::copy_file("source.txt", "sandbox/source.txt");

    // Iterate directory
    for (const auto& entry : fs::directory_iterator("sandbox")) {
        std::cout << entry.path() << '\n';
    }

    // Cleanup
    fs::remove_all("sandbox");
}

Embedded Applicability: Low

  • Depends on the OS file system abstraction layer (POSIX or Win32); bare-metal environments lack a file system.
  • Suitable for Embedded Linux (e.g., Buildroot/Yocto platforms) or host-side configuration/logging tools.
  • Header inclusion overhead is significant; not recommended for resource-constrained devices.
  • For embedded scenarios requiring a file system (e.g., FAT32 on SD card), consider lightweight alternatives like LittleFS.

Compiler Support

GCCClangMSVC
8719.12

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05