725b524c4892d0dce9af3a167337641e40aae1c2
[gapil.git] / listati / DirScan.c
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <dirent.h>        /* directory */
4 #include <stdlib.h>        /* C standard library */
5 #include <unistd.h>
6
7 /*
8  * Function DirScan: 
9  * 
10  * Input:  the directory name and a computation function
11  * Return: 0 if OK, -1 on errors
12  */
13 int DirScan(char * dirname, int(*compute)(struct dirent *)) 
14 {
15     DIR * dir;
16     struct dirent *direntry;
17
18     if ( (dir = opendir(dirname)) == NULL) {               /* oper directory */
19         printf("Opening %s\n", dirname);          /* on error print messages */
20         perror("Cannot open directory");                  /* and then return */
21         return -1;
22     }
23     fd = dirfd(dir);                                  /* get file descriptor */
24     fchdir(fd);                                          /* change directory */
25     /* loop on directory entries */
26     while ( (direntry = readdir(dir)) != NULL) {               /* read entry */
27         if (compute(direntry)) {                   /* execute function on it */
28             return -1;                                    /* on error return */
29         }
30     }
31     closedir(dir);
32     return 0;
33 }