Go to the first, previous, next, last section, table of contents.


Scanning the Content of a Directory

A higher-level interface to the directory handling functions is the scandir function. With its help one can select a subset of the entries in a directory, possibly sort them and get as the result a list of names.

Function: int scandir (const char *dir, struct dirent ***namelist, int (*selector) (struct dirent *), int (*cmp) (const void *, const void *))

The scandir function scans the contents of the directory selected by dir. The result in namelist is an array of pointers to structure of type struct dirent which describe all selected directory entries and which is allocated using malloc. Instead of always getting all directory entries returned, the user supplied function selector can be used to decide which entries are in the result. Only the entries for which selector returns a nonzero value are selected.

Finally the entries in the namelist are sorted using the user supplied function cmp. The arguments of the cmp function are of type struct dirent **. I.e., one cannot directly use the strcmp or strcoll function; see the function alphasort below.

The return value of the function gives the number of entries placed in namelist. If it is -1 an error occurred and the global variable errno contains more information on the error.

As said above the fourth argument to the scandir function must be a pointer to a sorting function. For the convenience of the programmer the GNU C library contains an implementation of a function which is very helpful for this purpose.

Function: int alphasort (const void *a, const void *b)
The alphasort function behaves like the strcmp function (see section String/Array Comparison). The difference is that the arguments are not string pointers but instead they are of type struct dirent **.

Return value of is less than, equal to, or greater than zero depending on the order of the two entries a and b.


Go to the first, previous, next, last section, table of contents.