scandir()

Updated: April 19, 2023

Scan a directory

Synopsis:

#include <dirent.h>

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

Arguments:

dirname
The name of the directory that you want to scan.
namelist
A pointer to a location where scandir() can store a pointer to the array of directory entries (of type struct dirent) that it builds.
select
A pointer to a user-supplied subroutine that scandir() calls to select which entries to include in the array. The select routine is passed a pointer to 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.

compar
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.

Library:

libc

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

Description:

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.

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

Returns:

The number of entries in the array, or -1 if an error occurred (errno is set).

Errors:

EACCES
Search permission is denied for the component of the path prefix of dirname, or read permission is denied for dirname.
ELOOP
A loop exists in symbolic links encountered during resolution of the dirname argument, or more than SYMLOOP_MAX symbolic links were encountered during resolution of the dirname argument.
ENAMETOOLONG
The length of a component of a pathname is longer than NAME_MAX.
ENOENT
A component of dirname doesn't name an existing directory, or dirname is an empty string.
ENOMEM
Insufficient storage space is available.
ENOSYS
The opendir() function isn't implemented for the filesystem underlying the path specified in dirname.
ENOTDIR
A component of dirname names an existing file that is neither a directory nor a symbolic link to a directory.
EOVERFLOW
One of the values to be returned or passed to a callback function can't be represented correctly.
EPERM
The process doesn't have the necessary ability to connect (PROCMGR_AID_CHANNEL_CONNECT).

Classification:

POSIX 1003.1

Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler Yes
Thread Yes