int scandir(const char *dir, struct dirent ***namelist,
int(*filter) (const struct dirent *),
int(*compar) (const struct dirent **, const struct dirent **));
There is the prototype of scandir(). The scandir() function scans the directory "dir",
calling "filter()" on each directory entry. Entries for which "filter()" return non-zero
are stored in strings allocated via malloc(), stored using qsort() with the comparison
function "compar()", and collected in array "namelist" which is allocated via malloc().
If "filter" is NULL, all entries are selected.
The alphasort() and versionsort() functions can be used as the comparison function "compar()".
The former sorts directory entries using "strcoll", the latter using "strverscmp" on the
strings "(*a)->d_name" and "(*d)->d_name".
I wrote a example to test this function. The code is following.
#include <dirent.h>
#include <stdio.h>
int selectAll(const struct dirent * d){
if (strcmp(d->d_name, ".")!=0 && strcmp(d->d_name, "..")!=0){
fprintf(stderr, "The directory entry [ %s ] is selected./n",
d->d_name);
return 1;
}else
return 0;
}
int main(int argc, char * argv[]){
struct dirent **namelist;
int n;
n = scandir(argv[1], &namelist, selectAll, alphasort);
if (n<0)
perror("scandir");
else{
while(n--){
printf("%s/n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
}
return 0;
}
From the above example, we can see the "scandir()" is a high order functor. There are two
functions can be plugged into the "scandir()" inside. Do you remember that (map proc ...) in
scheme. When I began to study programming algorithm in C, I had seen the technique. How wonderful
was I at that time! However, after learning lambda calculus, I known "the technique" is just
a rule in lambda calculus, called beta substitutes. Because scheme is a implementation of
lambda calculus, it is so natural to pass a function as parameter into another function. That
is its nature. But it is not the nature of C language in that C is a programming language which
need compile. In other words, its runtime environment is not full dynamic, some information
were changed and fixed into the binary program when product out binary codes. So, C programmer
has only way to pass a function pointer as parameter into another function.