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 *) );
If select is NULL, all the directory entries are included.
You can use alphasort() as the compar parameter to sort the array alphabetically.
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
This function is in libc.a, but not in libc.so (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.
Don't confuse the direct and dirent 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.
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
alphasort(), closedir(), dirent, free(), malloc(), opendir(), qsort(), readdir(), rewinddir(), seekdir(), telldir()