Learning Hub Search Ctrl K

Modern C++ › C++17

std::filesystem

Paths, directory iteration and file operations.

Since C++17 beginner #filesystem#path#directory_iterator#file-operations#error_code

Explanation

<filesystem> (namespace std::filesystem, often aliased to fs) gives portable access to files and directories, derived from Boost.Filesystem.

  • fs::path represents a path and handles separators: / joins (dir / "file.txt"), with accessors filename(), stem(), extension(), parent_path(), replace_extension().
  • Queries: exists, is_directory, is_regular_file, file_size, last_write_time.
  • Operations: create_directory, create_directories, copy, rename, remove, remove_all, current_path, temp_directory_path.
  • Iteration: directory_iterator (one level) and recursive_directory_iterator (whole tree).

Most functions come in two flavors: one that throws fs::filesystem_error and one that takes a std::error_code& and reports failure without throwing.

On GCC 8 you may need -lstdc++fs; GCC 9+ and MSVC need nothing extra.

Example

#include <filesystem>
#include <fstream>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    fs::path base = fs::temp_directory_path() / "fs_demo";
    fs::create_directories(base / "sub");                       // like mkdir -p

    { std::ofstream(base / "a.txt") << "hello"; }
    { std::ofstream(base / "sub" / "b.log") << "world!!"; }

    fs::path p = base / "a.txt";
    std::cout << p.filename() << " " << p.stem() << " " << p.extension() << "\n";   // "a.txt" "a" ".txt"
    std::cout << fs::exists(p) << " " << fs::file_size(p) << "\n";                  // 1 5

    for (const auto& entry : fs::recursive_directory_iterator(base)) {
        std::cout << (entry.is_directory() ? "[dir]  " : "[file] ")
                  << fs::relative(entry.path(), base).string() << "\n";
    }

    fs::copy_file(p, base / "copy.txt", fs::copy_options::overwrite_existing);
    fs::rename(base / "copy.txt", base / "renamed.txt");

    std::error_code ec;                                         // non-throwing form
    fs::remove(base / "does-not-exist", ec);
    if (ec) std::cout << "error: " << ec.message() << "\n";

    std::cout << "removed " << fs::remove_all(base) << " entries\n";
    return 0;
}

Common pitfalls

  • path::string() on Windows converts from wide characters and may lose non-ANSI characters; use wstring()/u8string() where it matters.
  • Iterating a directory while another process changes it gives unspecified results.
  • remove_all is irreversible and has no confirmation. Double-check the path.
  • Time-of-check/time-of-use races: if (exists(p)) open(p) is not atomic.
  • operator/ with an absolute right-hand side replaces the left path: fs::path("a") / "/b" is /b.
  • Streaming a path to cout prints it quoted.

Legacy vs modern

C++98 had no directory support: you used C’s fopen, POSIX opendir/stat, Win32 FindFirstFile, MFC’s CFileFind, or Boost.Filesystem, each different. std::filesystem unifies them. C++20 adds path::u8string() returning std::u8string.

Exercises

1. List all .cpp files under a directory tree.
for (const auto& e : fs::recursive_directory_iterator(root))
    if (e.is_regular_file() && e.path().extension() == ".cpp")
        std::cout << e.path() << "\n";