Scanning a Directory

While the family of routines (see directory(3)) starting with opendir(3) performs the functions that a programmer might need, they are somewhat tedious to code if you need them frequently enough. The scandir(3) and alphasort(3) routines assist in reducing the programmer effort required:

#include <sys/types.h>
#include <dirent.h>

int scandir(
    const char *dirname,
    struct dirent ***namelist,
    int (*select)(struct dirent *),
    int (*compar)(const void *, const void *));

int alphasort(const void *d1, const void *d2);

Function scandir(3) might look somewhat intimidating. However, once you spend a moment examining it, you will see that it is easy to use. The argument dirname is given the pathname of the directory that you want to ...

Get Advanced UNIX Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.