Skip to content

std::filesystem (C++17)

In a Nutshell

Platform-independent file system library: path concatenation and normalization, directory creation and traversal, file copy and deletion, permission and status queries -- say goodbye to stat() and opendir().

#include <filesystem>

Core API Quick Reference

OperationSignatureDescription
Path classclass pathPath construction, concatenation, decomposition (cross-platform separator handling)
Path concatenationpath operator/(const path& lhs, const path& rhs)p / "subdir" / "file.txt"
Current pathpath current_path()Get/set working directory
Directory iterationclass directory_iteratorIterate a single directory level
Recursive iterationclass recursive_directory_iteratorRecursively iterate subdirectories
File statusbool exists(const path& p)Check whether a path exists
File sizeuintmax_t file_size(const path& p)Get file size in bytes
Create directorybool create_directory(const path& p)Create a single directory
Create directoriesbool create_directories(const path& p)Recursively create the entire path
Copy filebool copy_file(const path& from, const path& to)Copy a single file
Removebool remove(const path& p)Remove a file or empty directory
Remove alluintmax_t remove_all(const path& p)Recursively remove a directory and its contents
Renamevoid rename(const path& old, const path& newp)Rename or move

Minimal Example

cpp
// Standard: C++17
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    fs::path p = fs::current_path() / "test.txt";
    std::cout << p << "\n";                      // full path
    std::cout << p.filename() << "\n";           // test.txt
    std::cout << p.extension() << "\n";          // .txt

    fs::create_directories("a/b/c");             // recursive creation
    std::cout << fs::exists("a/b") << "\n";      // true
    fs::remove_all("a");                         // recursive removal
}

Embedded Applicability: Low

  • Depends on OS file system abstraction layers (POSIX or Win32); bare-metal environments have no 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 extremely resource-constrained devices
  • For embedded scenarios that require a file system (e.g., FAT32 on SD card), consider lightweight alternatives such as LittleFS

Compiler Support

GCCClangMSVC
8719.12

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress