Library contents

C++ std::filesystem::directory_iterator

Enumerate immediate directory entries and filter their names by suffix.

A simple example

std::filesystem::directory_iterator

  1. Start with One folder containing a.txt and b.txt
  2. Do this List and sort its names
  3. Result a.txt, b.txt
Listing discovers the entries. Sorting makes their displayed order predictable.

Syntax

C++ 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
./lesson

Count 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.

From the programchar pattern[] = "/tmp/file-lesson-XXXXXX"
Result2
lesson.cpp
#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);
}
Output
2

The two CSV names pass the filter and the text note is excluded.

Advertisements

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.

Givenanna.pdf · li.pdf · team/plan.pdf
Worked result2

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.

Givenscore.pdf · parts/alto.pdf · parts/bass.pdf
Worked result1

What to watch for

Directory enumeration order is unspecified. Sort first if the order matters.

Documentation for std::filesystem::directory_iterator