C++ std::filesystem::directory_iterator
Enumerate immediate directory entries and filter their names by suffix.
A simple example
std::filesystem::directory_iterator
- Start with One folder containing a.txt and b.txt
- Do this List and sort its names
- Result a.txt, b.txt
Syntax
fs::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
./lessonCount only the invoices in a folder
A market stall saves two CSV invoices and a text note in the same folder. Count just the CSV entries for the daily summary without depending on the order returned by the filesystem.
#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 {
for (auto name : {"a.csv", "b.csv", "notes.txt"}) std::ofstream(base / name) << "entry";
int count = 0;
for (const auto& entry : fs::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);
}
2
The two CSV names pass the filter and the text note is excluded.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files in the top-level folder only. Do not count subfolders as files.
Inventory rehearsal parts
A school stores one score and two parts in a subfolder. Count regular files in the top-level folder only. Do not count subfolders as files.
What to watch for
Directory enumeration order is unspecified. Sort first if the order matters.