Here is a revised version of the directory lister found above
(see section Simple Program to List a Directory). Using the scandir
function we
can avoid using the functions which directly work with the directory
contents. After the call the found entries are available for direct
used.
#include <stdio.h> #include <dirent.h> static int one (struct dirent *unused) { return 1; } int main (void) { struct dirent **eps; int n; n = scandir ("./", &eps, one, alphasort); if (n >= 0) { int cnt; for (cnt = 0; cnt < n; ++cnt) puts (eps[cnt]->d_name); } else perror ("Couldn't open the directory"); return 0; }
Please note the simple selector function for this example. Since
we want to see all directory entries we always return 1
.
Go to the first, previous, next, last section, table of contents.