C++ std::filesystem::recursive_directory_iterator
Walk a directory tree and select matching regular files.
A simple example
std::filesystem::recursive_directory_iterator
- Start with Folder a contains b/c.txt
- Do this Visit descendants
- Result The walk reaches c.txt
Syntax
fs::recursive_directory_iterator(base)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 on macOS or Linux with a POSIX shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonFind a receipt below the month folder
A treasurer has one receipt in a month folder and a note beside that folder. A recursive inventory should locate the nested CSV receipt while leaving the unrelated note out of its total.
#include <unistd.h>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace fs = std::filesystem;
int main() {
char pattern[] = "/tmp/file-lesson-XXXXXX";
if (!mkdtemp(pattern)) throw std::runtime_error("Cannot create workspace");
fs::path base(pattern);
try {
fs::create_directory(base / "March");
std::ofstream(base / "March" / "dues.csv") << "paid";
std::ofstream(base / "notes.txt") << "note";
int count = 0;
for (const auto& entry : fs::recursive_directory_iterator(base))
if (entry.is_regular_file() && entry.path().extension() == ".csv") ++count;
std::cout << count << '\n';
} catch (...) {
fs::remove_all(base);
throw;
}
fs::remove_all(base);
}
1
The month folder contributes one matching receipt below the top level.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files throughout the folder tree, including its subfolders.
Inventory rehearsal parts
A school stores one score and two parts in a subfolder. Count regular files throughout the folder tree, including its subfolders.
What to watch for
Following symbolic links during recursion can revisit directories. Choose link handling deliberately.
Documentation for std::filesystem::recursive_directory_iterator