Caution: This version of this document is no longer maintained. For the latest documentation, see


Scan a directory


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

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


The name of the directory that you want to scan.
A pointer to a location where scandir() can store a pointer to the array of directory entries (of type struct direct *) that it builds.
A pointer to a user-supplied subroutine that scandir() calls to select which entries to included in the array. The select routine is passed a pointer to a directory entry (a struct dirent) and should return a nonzero value if the directory entry is to be included in the array.

If select is NULL, all the directory entries are included.

A pointer to a user-supplied subroutine that's passed to qsort() to sort the completed array. If this pointer is NULL, the array isn't sorted.

You can use alphasort() as the compar parameter to sort the array alphabetically.



Use the -l c option to qcc to link against this library. This library is usually included automatically.

Note: This function is in libc.a, but not in (in order to save space).


The scandir() function reads the directory dirname and builds an array of pointers to directory entries, using malloc() to allocate the space. The scandir() function returns the number of entries in the array, and stores a pointer to the array in the location referenced by namelist.

Note: Don't confuse the direct and dirent structures:
  • The entries in the array are pointers to direct structures.
  • The argument to the select function is a pointer to a dirent structure.
  • The arguments to the compar() function are used as pointers to direct structures.

The struct direct is defined as:

struct direct {
    unsigned long d_fileno;
    unsigned short d_reclen;
    unsigned short d_namlen;
    char d_name[1];

You can deallocate the memory allocated for the array by calling free(). Free each pointer in the array, and then free the array itself.


The number of entries in the array, or -1 if the directory can't be opened for reading, or malloc() can't allocate enough memory to hold all the data structures.


Legacy Unix

Cancellation point Yes
Interrupt handler No
Signal handler Yes
Thread Yes

See also:

alphasort(), closedir(), dirent, free(), malloc(), opendir(), qsort(), readdir(), rewinddir(), seekdir(), telldir()