Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::filesystem::recursive_directory_iterator: recursive tree traversal

std::filesystem::recursive_directory_iterator is a single-pass input iterator over entries in a directory and its subdirectories.

Version: C++23

Syntax

class std::filesystem::recursive_directory_iterator {
public:
    using iterator_category = std::input_iterator_tag;
    recursive_directory_iterator() noexcept;
    explicit recursive_directory_iterator(const std::filesystem::path& p);
    int depth() const;
    bool recursion_pending() const;
    recursive_directory_iterator& operator++();
    void pop();
    void disable_recursion_pending();
};

std::filesystem::recursive_directory_iterator(p) from <filesystem> visits directory_entry objects below p, descending into subdirectories automatically. depth() is 0 for entries immediately in the starting directory, 1 one level below, and so on; entry order at each level is unspecified.

The example creates one file at depth 0 and another in a subdirectory, counts regular files and the maximum depth, and prints 2 1. Before incrementing, disable_recursion_pending() can skip descendants of the current directory, while pop() ends the current level and resumes at its parent.

Directory symlinks are not followed by default; follow_directory_symlink enables this and a cycle can then make the end unreachable. skip_permission_denied skips access denials. This is an input iterator; calling depth, options, pop, or recursion controls on an end iterator is undefined behavior.

Examples

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

int main() {
    namespace fs = std::filesystem;
    const fs::path root = fs::temp_directory_path() / "cktis-cpp-ref-recursive-iterator";
    std::error_code ignored;
    fs::remove_all(root, ignored);
    fs::create_directories(root / "sub");
    std::ofstream(root / "top.txt") << "top";
    std::ofstream(root / "sub" / "nested.txt") << "nested";

    int files = 0;
    int max_depth = 0;
    for (fs::recursive_directory_iterator it(root), end; it != end; ++it) {
        if (it->is_regular_file()) {
            ++files;
            max_depth = std::max(max_depth, it.depth());
        }
    }
    std::cout << files << ' ' << max_depth << '\n';

    fs::remove_all(root, ignored);
}

Result

2 1

std::filesystem::recursive_directory_iterator → 2 1

Sources