CKTIS / C++
std::filesystem::directory_iterator: a single pass over a directory
std::filesystem::directory_iterator is an input iterator over a directory’s immediate entries and does not descend into subdirectories automatically.
Version: C++23
Syntax
class std::filesystem::directory_iterator {
public:
using iterator_category = std::input_iterator_tag;
directory_iterator() noexcept;
explicit directory_iterator(const std::filesystem::path& p);
const std::filesystem::directory_entry& operator*() const;
directory_iterator& operator++();
};std::filesystem::directory_iterator(p) from <filesystem> exposes a sequence of directory_entry objects for files immediately in p. It omits . and .., uses an unspecified order, and its default constructor creates the sole valid end value.
The example creates two files totaling three bytes, iterates without depending on order, and prints 2 3. This is an input iterator: it is single-pass, copies do not provide two independent cursors, and the end value is not dereferenceable.
If the directory changes during iteration, whether added or removed entries are observed is unspecified. A directory_entry can contain cached attributes, and its path can be a dangling symlink. An error or advancing past the last element makes the iterator equal to end; skip_permission_denied can turn a construction-time access denial into an empty range.
Examples
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iostream>
int main() {
namespace fs = std::filesystem;
const fs::path root = fs::temp_directory_path() / "cktis-cpp-ref-directory-iterator";
std::error_code ignored;
fs::remove_all(root, ignored);
fs::create_directory(root);
std::ofstream(root / "a.txt") << "x";
std::ofstream(root / "b.txt") << "yz";
int regular_files = 0;
std::uintmax_t bytes = 0;
for (const fs::directory_entry& entry : fs::directory_iterator(root)) {
if (entry.is_regular_file()) {
++regular_files;
bytes += entry.file_size();
}
}
std::cout << regular_files << ' ' << bytes << '\n';
fs::remove_all(root, ignored);
}
Result
2 3
std::filesystem::directory_iterator → 2 3