cpp17 · medium

C++17: std::filesystem

std::filesystem (C++17, standardized from Boost.Filesystem) provides a portable, object-oriented API over paths, files, and directories. The central type fs::path normalizes platform separators, supports Unicode, and composes with operator/; free functions query and manipulate the tree — exists, is_directory, file_size, copy, rename, remove, create_directories (the equivalent of mkdir -p) — while directory_iterator and recursive_directory_iterator walk folders. Most operations come in two forms: a throwing overload that raises std::filesystem::filesystem_error and an overload taking a std::error_code& that reports failure without throwing, the latter preferred in hot paths or when a missing file is expected. Key gotchas: directory iteration order is unspecified, symlinks require care (is_directory follows them while symlink_status inspects the link itself), file_size on a directory is an error, and checking exists() before opening is a TOCTOU race because it is not atomic with respect to other processes.

🔑 Key line

C++17 std::filesystem gives a portable path type plus free functions (exists, file_size, create_directories, recursive_directory_iterator); each op has a throwing and an error_code form — iteration order is unspecified and check-then-use is a TOCTOU race.

The code

#include <filesystem>
namespace fs = std::filesystem;
fs::path p = "data/logs";
if (fs::exists(p) && fs::is_directory(p))
for (auto& e : fs::recursive_directory_iterator(p))
if (e.path().extension() == ".log")
total += fs::file_size(e);
fs::create_directories("out/2026/06"); // mkdir -p
std::error_code ec; fs::remove(p, ec); // non-throwing form

What this lesson walks through

  1. 01A portable filesystem API
  2. 02Errors: throwing vs error_code
  3. 03Gotcha — throws by default + TOCTOU
  4. 04Gotchas

std::filesystem (C++17, from Boost.Filesystem) gives a portable, object-oriented API over paths, files, and directories. fs::path handles platform separators and Unicode; free functions query and manipulate the tree (exists, is_directory, file_size, create_directories, copy, remove, rename). Directory iterators walk a folder, recursive_directory_iterator descends subfolders.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of C++17: std::filesystem and 100+ animated C++ interview lessons.

← Previous
C++17: Guaranteed Copy Elision
Next →
C++17: Parallel STL Algorithms