Aggiornamento note copyright
[gapil.git] / sources / dir_scan.c
1 /* dir_scan.c
2  * 
3  * Copyright (C) 2002 Simone Piccardi
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or (at
8  * your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /*****************************************************************************
20  *
21  * File dir_scan.c: routine for directory scan 
22  *
23  * Author: S. Piccardi Jan. 2003
24  *
25  *****************************************************************************/
26 #include <sys/types.h>   /* primitive system data types */
27 #include <sys/stat.h>    /* file characteristics constants and functions */
28 #include <dirent.h>      /* directory operation constants and functions */
29 #include <stdlib.h>      /* C standard library */
30 #include <stdio.h>       /* standard I/O library */
31 #include <unistd.h>      /* unix standard library */
32
33 /*
34  * Function dir_scan: 
35  * 
36  * Scan all entries in a directory, executing the provided function
37  * on each one.
38  *
39  * Input:  the directory name and a computation function
40  * Return: 0 if OK, -1 on errors
41  */
42 int dir_scan(char * dirname, int(*compute)(struct dirent *)) 
43 {
44     DIR * dir;
45     struct dirent *direntry;
46     int fd;
47
48     if ( (dir = opendir(dirname)) == NULL) {               /* oper directory */
49         printf("Opening %s\n", dirname);          /* on error print messages */
50         perror("Cannot open directory");                  /* and then return */
51         return -1;
52     }
53     fd = dirfd(dir);                                  /* get file descriptor */
54     fchdir(fd);                                          /* change directory */
55     /* loop on directory entries */
56     while ( (direntry = readdir(dir)) != NULL) {               /* read entry */
57         if (compute(direntry)) {                   /* execute function on it */
58             return -1;                                    /* on error return */
59         }
60     }
61     closedir(dir);
62     return 0;
63 }