Table of Contents

<filesystem>

<filesystem> provides portable file and directory operations: std::filesystem::path, std::filesystem::exists, std::filesystem::is_regular_file, std::filesystem::directory_iterator, etc. It abstracts away differences between POSIX and Windows paths.

Use it for any code that creates, lists, or inspects files and directories. It's far better than hand-written string manipulation with mkdir or opendir.

Example

This example iterates through all entries in the current directory, printing their names portably across platforms.

// compile: g++ -std=c++17 -o filesystemexample filesystemexample.cpp
// run: ./filesystemexample
// description: list files in a directory
 
#include <filesystem>
#include <iostream>
 
namespace fs = std::filesystem;
 
int main() {
    fs::path dir(".");
 
    if (fs::exists(dir) && fs::is_directory(dir)) {
        for (const auto& entry : fs::directory_iterator(dir)) {
            std::cout << entry.path().filename().string() << "\n";
        }
    }
 
    return 0;
}