Library contents

C opendir and readdir

Enumerate immediate directory entries and filter their names by suffix.

A simple example

opendir and readdir

  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
readdir(directory)
Run these examples in C

Save one example at a time as lesson.c. Use C17 on macOS or Linux with a POSIX shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -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 folder[] = "/tmp/market-XXXXXX", path[128]
Result2
lesson.c
#define _POSIX_C_SOURCE 200809L
#if defined(__APPLE__)
#define _DARWIN_C_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>

int main(void) {
    char folder[] = "/tmp/market-XXXXXX", path[128];
    if (!mkdtemp(folder)) return 1;
    const char *names[] = {"a.csv", "b.csv", "note"};
    int ok = 1, count = 0;
    for (int i = 0; i < 3 && ok; i++) {
        snprintf(path, sizeof path, "%s/%s", folder, names[i]);
        FILE *file = fopen(path, "w");
        ok = file && fclose(file) == 0;
    }
    DIR *dir = ok ? opendir(folder) : NULL;
    if (dir) {
        struct dirent *entry;
        errno = 0;
        while ((entry = readdir(dir)) != NULL) {
            const char *suffix = strrchr(entry->d_name, '.');
            if (suffix && strcmp(suffix, ".csv") == 0) count++;
        }
        ok = errno == 0;
        closedir(dir);
    } else ok = 0;
    for (int i = 0; i < 3; i++) {
        snprintf(path, sizeof path, "%s/%s", folder, names[i]);
        unlink(path);
    }
    rmdir(folder);
    if (ok) printf("%d\n", count);
    return ok ? 0 : 1;
}
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

These C examples use POSIX file APIs on macOS or Linux. Directory enumeration order is unspecified. Sort first if the order matters.

Documentation for opendir and readdir