typestar

Walking a directory in C

opendir, readdir, closedir: three calls and a loop.

#include <dirent.h>
#include <stdio.h>
#include <string.h>

int count_entries(const char *path) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return -1;
    }

    int count = 0;
    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0) {
            continue;
        }
        printf("%s\n", entry->d_name);
        count++;
    }
    closedir(dir);
    return count;
}

How it works

  1. readdir returns NULL when the entries run out.
  2. The dot and dot-dot entries come back too.
  3. The returned struct is reused, so copy what you keep.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
413
Tokens
135
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 2 of 2 in Files & directories, step 12 of 14 in Systems programming.

← Previous Next →

Walking a directory in other languages