Skip to content
systemcoding.dev
Systems Programming

Build an ls Clone with Long Listing Output

Build an ls -l clone in C with opendir, readdir and lstat: mode strings, owner names, sizes and timestamps, using POSIX.1-2024 calls on Linux with glibc 2.41.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, GNU and Rust logos.

The ls -l command looks like a formatting job, and that is what makes it a good exercise: every column on the screen comes from a different system call or library function. The file type and permissions come from lstat, the owner and group names come from the user and group databases, the date comes from the modification time, and the order comes from sorting the names yourself, because directory order is whatever the filesystem happens to return. This post builds a small ls -l in C against POSIX.1-2024 on Linux with glibc 2.41, and every decision in it maps to a call you can read about in [the POSIX specification for lstat](https://pubs.opengroup.org/onlinepubs/9799919799/functions/lstat.html). If you have not yet met the file metadata calls, the earlier posts on file I/O in this cluster cover stat and file descriptors; here we assume you can read a man page and compile with cc.

What each column of ls -l comes from

A long listing line has seven parts. Knowing the source of each one tells you the order to write the code in.

ColumnExampleSource
Type and mode-rw-r--r--st_mode from lstat
Link count1st_nlink
Ownerpetegetpwuid(st_uid)
Groupstaffgetgrgid(st_gid)
Size4096st_size
TimeNov 23 10:41st_mtim through localtime_r and strftime
Namenotes.txtd_name from readdir

The type character is the first one that surprises people. A regular file gets -, a directory d, a symbolic link l, and the others (c, b, p, s) are character devices, block devices, FIFOs and sockets. All of them are tested with the macros from <sys/stat.h>: S_ISREG, S_ISDIR, S_ISLNK, S_ISCHR, S_ISBLK, S_ISFIFO and S_ISSOCK. Never compare st_mode & S_IFMT against a literal by hand unless you have to, because the macros exist so you do not depend on the bit layout.

Use lstat, not stat

ls -l shows a symbolic link as a link, so the clone has to call lstat, which describes the link itself, and not stat, which follows it and describes the target. With stat, a link to a directory would print a d and a link to a missing file would fail outright. With lstat, the link prints as l and its size is the length of the path it stores.

To print name -> target the way ls does, call readlink on the path. It does not add a terminating NUL byte, which is the classic bug in this function: you must reserve one byte, pass sizeof buf - 1, and write the NUL yourself.

Build the mode string

The permission bits are three groups of three: read, write and execute for the owner, the group and everyone else. The setuid, setgid and sticky bits replace the execute character with s, s and t (and upper case S or T when the execute bit underneath is not set). The helper below handles all of that.

ls_mode.cc
#include <sys/stat.h>

void mode_string(mode_t m, char out[11])
{
    out[0] = S_ISDIR(m)  ? 'd' :
             S_ISLNK(m)  ? 'l' :
             S_ISCHR(m)  ? 'c' :
             S_ISBLK(m)  ? 'b' :
             S_ISFIFO(m) ? 'p' :
             S_ISSOCK(m) ? 's' : '-';

    out[1] = (m & S_IRUSR) ? 'r' : '-';
    out[2] = (m & S_IWUSR) ? 'w' : '-';
    out[3] = (m & S_ISUID) ? ((m & S_IXUSR) ? 's' : 'S')
                           : ((m & S_IXUSR) ? 'x' : '-');

    out[4] = (m & S_IRGRP) ? 'r' : '-';
    out[5] = (m & S_IWGRP) ? 'w' : '-';
    out[6] = (m & S_ISGID) ? ((m & S_IXGRP) ? 's' : 'S')
                           : ((m & S_IXGRP) ? 'x' : '-');

    out[7] = (m & S_IROTH) ? 'r' : '-';
    out[8] = (m & S_IWOTH) ? 'w' : '-';
    out[9] = (m & S_ISVTX) ? ((m & S_IXOTH) ? 't' : 'T')
                           : ((m & S_IXOTH) ? 'x' : '-');
    out[10] = '\0';
}

The function writes eleven bytes: ten characters and the NUL. A mode of 0755 on a directory yields drwxr-xr-x, and 04755 on a regular file yields -rwsr-xr-x, which is what /usr/bin/passwd looks like on many systems.

Read the directory and sort it

opendir returns a DIR *, and readdir returns one struct dirent * per call until it returns NULL. Two details trip people up. First, readdir returns NULL both at the end and on error, and the only way to tell the cases apart is to set errno = 0 before the loop and check it after. Second, the returned pointer may point at a buffer that the next readdir call overwrites, so copy the name with strdup if you keep it.

Plain ls hides names that start with a dot. The clone does the same unless it is given -a, and it sorts with strcmp. Real ls sorts using the locale's collation rules, which is why its order can differ from strcmp order on a machine with LANG=en_US.UTF-8. Calling setlocale(LC_ALL, "") and sorting with strcoll reproduces that, and that is the version we use.

The complete program

myls.cc
#define _POSIX_C_SOURCE 200809L
#include <dirent.h>
#include <errno.h>
#include <grp.h>
#include <locale.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

void mode_string(mode_t m, char out[11]);

static int by_name(const void *a, const void *b)
{
    return strcoll(*(char *const *)a, *(char *const *)b);
}

static void print_entry(const char *dir, const char *name)
{
    char path[4096];
    snprintf(path, sizeof path, "%s/%s", dir, name);

    struct stat st;
    if (lstat(path, &st) == -1) {
        perror(path);
        return;
    }

    char mode[11];
    mode_string(st.st_mode, mode);

    struct passwd *pw = getpwuid(st.st_uid);
    struct group  *gr = getgrgid(st.st_gid);

    char when[32];
    struct tm tm;
    localtime_r(&st.st_mtim.tv_sec, &tm);
    strftime(when, sizeof when, "%b %e %H:%M", &tm);

    printf("%s %3lu %-8s %-8s %8lld %s %s",
           mode, (unsigned long)st.st_nlink,
           pw ? pw->pw_name : "?", gr ? gr->gr_name : "?",
           (long long)st.st_size, when, name);

    if (S_ISLNK(st.st_mode)) {
        char target[4096];
        ssize_t n = readlink(path, target, sizeof target - 1);
        if (n >= 0) {
            target[n] = '\0';
            printf(" -> %s", target);
        }
    }
    putchar('\n');
}

int main(int argc, char **argv)
{
    setlocale(LC_ALL, "");
    const char *dir = argc > 1 ? argv[1] : ".";

    DIR *d = opendir(dir);
    if (!d) {
        perror(dir);
        return 1;
    }

    char **names = NULL;
    size_t count = 0, cap = 0;
    struct dirent *e;
    errno = 0;
    while ((e = readdir(d)) != NULL) {
        if (e->d_name[0] == '.')
            continue;
        if (count == cap) {
            cap = cap ? cap * 2 : 16;
            names = realloc(names, cap * sizeof *names);
            if (!names) {
                perror("realloc");
                return 1;
            }
        }
        names[count++] = strdup(e->d_name);
    }
    if (errno != 0)
        perror("readdir");
    closedir(d);

    qsort(names, count, sizeof *names, by_name);
    for (size_t i = 0; i < count; i++) {
        print_entry(dir, names[i]);
        free(names[i]);
    }
    free(names);
    return 0;
}

Build it with cc -std=c11 -Wall -Wextra -o myls myls.c ls_mode.c. In a directory holding a script, a notes file, a subdirectory and a link, the output looks like this. The owner, group, sizes and dates will differ on your machine.

Text
-rwxr-xr-x   1 pete     staff         212 Nov 23 10:41 build.sh
lrwxrwxrwx   1 pete     staff           9 Nov 23 10:42 latest -> notes.txt
-rw-r--r--   1 pete     staff        1830 Nov 22 18:05 notes.txt
drwxr-xr-x   2 pete     staff        4096 Nov 20 09:12 src

The %e conversion pads the day of the month with a space, which keeps the time column aligned for days 1 through 9. The size of the latest link is nine because it stores the nine bytes of notes.txt.

Where this differs from the real ls

The clone is honest about a handful of shortcuts, and a reader who plans to extend it should know them.

  • Time format. GNU ls prints the year instead of the time for files older than about six months, using st_mtim against the current time. The clone always prints the time.

  • Total line. ls -l starts with total N, the number of 1024-byte blocks used, taken from st_blocks. The clone omits it.

  • ACL and SELinux markers. A . or + after the mode string signals an extended attribute or ACL. Detecting it takes getxattr or acl_get_file.

  • Device numbers. For character and block devices, ls -l replaces the size column with the major and minor numbers from st_rdev, which you read with the major and minor macros from <sys/sysmacros.h>.

  • Race conditions. The directory can change between readdir and lstat. A file that vanishes produces an ENOENT from lstat, which the clone prints with perror and moves on from. That is the correct behavior, and it is the same thing ls does.

The openat and fstatat calls are the more careful way to avoid path-building and races: open the directory once, then call fstatat(dirfd(d), name, &st, AT_SYMLINK_NOFOLLOW) for each entry, so a rename of a parent directory mid-listing cannot redirect you. The glibc manual's chapter on reading directories documents the same pattern for readdir.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.