Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 171 ยท Input/Output and Files

The Filesystem Library

Learn C++ std::filesystem - build and split paths, check files, create directories, list folders recursively, copy, rename and remove files, and handle errors safely.

Streams such as std::ifstream read and write the contents of files, but they can't answer questions about the file system itself: Does this folder exist? How big is that file? Which .log files are in this directory? Before C++17 you needed platform APIs (opendir on Linux, FindFirstFile on Windows) or a library like Boost for that. Since C++17 the standard has <filesystem>, a portable library for paths, directories and file operations.

In this lesson you'll build and take apart paths, query files, create and list directories (also recursively), copy, rename and delete files, and handle errors in the two styles the library offers. Every example creates its own files, because each run of our editor starts with a fresh, empty working directory, and everything it writes disappears afterwards. If you haven't read Reading and Writing Text Files yet, skim it first: we use std::ofstream to create test files.

Getting started: the namespace and std::filesystem::path

Everything lives in the namespace std::filesystem. Writing that out every time is tiring, so almost all code introduces a short namespace alias:

C++
#include <filesystem>

namespace fs = std::filesystem;   // fs::path, fs::exists, ...

The central type is fs::path. A path is just a name: creating one never touches the disk, and a path can refer to something that doesn't exist yet. You build paths from strings, and you join them with operator/, which inserts the right separator for you. Member functions split a path into its parts:

Member For /home/ana/report.final.txt
root_path() /
parent_path() /home/ana
filename() report.final.txt
stem() report.final
extension() .txt (with the dot)
C++ Building and splitting paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A few details worth knowing:

  • extension() returns only the last extension, with its dot. For archive.tar.gz it's .gz, and the stem is archive.tar. A file named .bashrc has no extension at all: its stem is .bashrc.
  • p / "x" appends a component, but if the right side is an absolute path it replaces the left side: fs::path{"/a"} / "/b" is /b. Check user-provided names before joining them.
  • lexically_normal() and lexically_relative() work on the text only. They don't follow symbolic links and don't care whether anything exists.
  • To print a path, call .string(). std::println("{}", p) doesn't compile in C++23 (a std::formatter for paths arrives in C++26), and streaming a path with std::cout << p puts it in quotes (it uses std::quoted), which surprises people in log files.

On Windows, fs::path stores wchar_t text and uses \ as its preferred separator, while POSIX systems store char and use /. / works as a separator on Windows too, and p.generic_string() always gives you forward slashes. For non-ASCII names, p.u8string() returns UTF-8 portably.

Asking questions about files

The free functions in std::filesystem do touch the disk. The most common ones are:

  • fs::exists(p): is there anything at this path?
  • fs::is_regular_file(p), fs::is_directory(p), fs::is_symlink(p): what kind of entry is it?
  • fs::file_size(p): size in bytes (only for regular files).
  • fs::last_write_time(p): modification time as an fs::file_time_type.
  • fs::current_path(): the program's working directory; fs::absolute(p) resolves a relative path against it.
C++ Creating a file and querying it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The exists check can't be used to avoid that exception in robust code, by the way. Between your check and your next call, another program can delete or create the file. That gap is called a TOCTOU race (time of check to time of use). Robust code simply attempts the operation and handles the error, which brings us to the two error styles.

Two ways to handle errors: exceptions or std::error_code

Almost every operation comes in two overloads:

  1. Without an extra argument, failures throw fs::filesystem_error (derived from std::system_error). It carries an error code, a message and up to two paths.
  2. With a trailing std::error_code& argument, the function is noexcept-ish: it never throws for file system errors and instead stores the error in the code (and clears it on success). Functions that return a value return a sentinel on failure, such as static_cast<std::uintmax_t>(-1) for file_size.

Use exceptions when a failure means "this whole task can't continue", and error codes when failure is expected and routine, like probing many files in a loop. See Error Handling Without Exceptions for the bigger picture.

C++
std::error_code ec;
auto size = fs::file_size("maybe.txt", ec);
if (ec) {
    std::println("could not read size: {}", ec.message());
} else {
    std::println("{} bytes", size);
}

Creating directories and listing their contents

fs::create_directory(p) creates one directory and fails if the parent is missing. fs::create_directories(p) creates every missing level, like mkdir -p. Both return true if they created something and false if the directory already existed, so calling them twice is safe.

To list a directory, loop over a fs::directory_iterator. Each element is an fs::directory_entry that holds the path and caches some status information, so entry.is_directory() is often cheaper than fs::is_directory(entry.path()). fs::recursive_directory_iterator walks the whole tree and tells you how deep it is with depth().

C++ Creating and walking a directory tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice the std::ranges::sort calls. The order in which a directory iterator returns entries is unspecified: it's whatever the operating system's directory listing produces, which is often creation order on one system and hash order on another. If you show results to people or compare them in tests, sort them first.

When you need to know how deep the recursive iterator currently is (for indentation, for example), call it.depth() on the iterator itself, and it.disable_recursion_pending() to skip descending into the current directory (handy for ignoring .git or node_modules). Because those are iterator members, you need an explicit iterator loop:

C++
for (auto it = fs::recursive_directory_iterator{root}; it != fs::recursive_directory_iterator{}; ++it) {
    if (it->is_directory() && it->path().filename() == "node_modules") {
        it.disable_recursion_pending();        // don't walk into it
    }
    std::println("{}{}", std::string(it.depth() * 2, ' '), it->path().filename().string());
}

By default the recursive iterator doesn't follow directory symlinks (which protects you from loops) and throws if it meets a directory it may not read. Pass fs::directory_options::skip_permission_denied to quietly skip those instead.

Copying, renaming and removing

The modifying operations read like their shell counterparts:

Function Does Notes
fs::copy_file(from, to, options) copies one file fails if to exists, unless copy_options::overwrite_existing or update_existing
fs::copy(from, to, options) copies files or directories add copy_options::recursive for whole trees
fs::rename(from, to) renames or moves replaces an existing file to on POSIX
fs::remove(p) deletes a file or an empty directory returns false if nothing was there
fs::remove_all(p) deletes a whole tree returns how many entries it removed
fs::resize_file(p, n) truncates or extends a file
C++ Copy, rename and remove

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

fs::remove_all is the equivalent of rm -rf: there is no trash bin and no confirmation. Never call it on a path built from user input or from a variable that might be empty or /. A common safety net is to check that the target lies inside a directory your program owns before deleting.

Temporary files, the working directory and canonical paths

fs::temp_directory_path() returns the system's folder for scratch files (/tmp on Linux, the TEMP directory on Windows). The library doesn't generate unique file names for you, so combine the temp directory with a name that includes something unique, such as the process ID or a random number, and remove the file when you're done (an RAII guard is the cleanest way).

fs::current_path() returns the working directory, and fs::current_path(p) changes it for the whole process, which is global state you should rarely touch. fs::canonical(p) returns an absolute path with symbolic links, . and .. resolved; unlike lexically_normal, it consults the disk and throws if the path doesn't exist. fs::weakly_canonical(p) resolves as much as exists and keeps the rest.

C++ A temporary working folder with RAII cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

fs::space(p) reports capacity, free and available bytes for the volume that holds p; available is what an unprivileged program can actually use.

Permissions, time stamps and other details

  • fs::status(p).permissions() returns an fs::perms bit mask (owner_read, group_write, others_exec, ...), and fs::permissions(p, perms, fs::perm_options::add) changes it. On Windows only the read-only flag really maps to anything.
  • fs::last_write_time(p) returns fs::file_time_type, a std::chrono::time_point on a special file clock. In C++20 you can convert it with std::chrono::clock_cast<std::chrono::system_clock>(t) (include <chrono>) and format it with std::format("{:%F %T}", ...); see Dates, Times and Durations.
  • fs::equivalent(a, b) tells you whether two paths refer to the same file (for example through a symlink).
  • fs::is_empty(p) works for both empty files and empty directories.
  • fs::hard_link_count, fs::create_symlink and fs::read_symlink cover links; creating symlinks on Windows needs special privileges.

Common mistakes

  • Treating a path as a string. Use /, filename(), extension() and friends instead of searching for '/' or '.' by hand; hand-rolled parsing breaks on archive.tar.gz, .gitignore and Windows paths.
  • Assuming iteration order. Sort directory listings before showing or comparing them.
  • Check-then-act. if (!exists(p)) create(p) is racy; just call create_directories (which already handles "exists") or catch the error.
  • Forgetting that relative paths depend on the working directory. A program started from another folder sees different files. Build paths from a known base (a config value or the executable's location).
  • Letting filesystem_error escape from a destructor. Use the std::error_code overloads in cleanup code, as TempDir does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fs::path{"backup/db.tar.gz"}.extension() return?

    extension() returns only the last extension, including the dot. The stem is "db.tar".
  2. 2. What happens when you call fs::file_size on a path that doesn't exist, without an error_code argument?

    The throwing overload reports failures as filesystem_error. Pass a std::error_code& to get a sentinel value and an error code instead.
  3. 3. You list a directory with fs::directory_iterator and print the names. On another computer they come out in a different order. Why?

    The library returns entries in whatever order the operating system lists them. Collect and sort them when you need a stable order.
  4. 4. Directory work contains one file. What does fs::remove("work") do?

    remove() refuses non-empty directories and reports an error. Use remove_all() to delete a whole tree.
  5. 5. What is fs::path{"/srv/data"} / "/etc/passwd"?

    Appending an absolute path replaces the left side. Validate untrusted names before joining them to a base directory.

Summary

  • Include <filesystem> and alias it: namespace fs = std::filesystem;.
  • fs::path is a name, not a file: join with /, split with parent_path(), filename(), stem() and extension(), and clean up with lexically_normal().
  • exists, is_regular_file, is_directory, file_size and last_write_time query the disk.
  • create_directories makes nested folders; directory_iterator and recursive_directory_iterator list them in an unspecified order.
  • copy_file, copy (with copy_options), rename, remove and remove_all modify the file system; remove_all is rm -rf.
  • Every operation either throws fs::filesystem_error or, with a std::error_code& argument, reports errors without throwing. Prefer attempting an operation over check-then-act.

Next: Dates, Times and Durations with chrono, where you'll measure time, work with calendar dates and format both.