Messi gli esempi nel testo e usata daemon dove serve nei server
[gapil.git] / sources / DirScan.c
1 /* DirScan.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 DirScan.c: routine for directory scan 
22  *
23  * Author: S. Piccardi Jan. 2003
24  *
25  * $Id: DirScan.c,v 1.2 2003/01/04 17:24:30 piccardi Exp $
26  *
27  *****************************************************************************/
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <dirent.h>        /* directory */
31 #include <stdlib.h>        /* C standard library */
32 #include <stdio.h>
33 #include <unistd.h>
34
35 /*
36  * Function DirScan: 
37  * 
38  * Scan all entries in a directory, executing the provided function
39  * on each one.
40  *
41  * Input:  the directory name and a computation function
42  * Return: 0 if OK, -1 on errors
43  */
44 int DirScan(char * dirname, int(*compute)(struct dirent *)) 
45 {
46     DIR * dir;
47     struct dirent *direntry;
48     int fd;
49
50     if ( (dir = opendir(dirname)) == NULL) {               /* oper directory */
51         printf("Opening %s\n", dirname);          /* on error print messages */
52         perror("Cannot open directory");                  /* and then return */
53         return -1;
54     }
55     fd = dirfd(dir);                                  /* get file descriptor */
56     fchdir(fd);                                          /* change directory */
57     /* loop on directory entries */
58     while ( (direntry = readdir(dir)) != NULL) {               /* read entry */
59         if (compute(direntry)) {                   /* execute function on it */
60             return -1;                                    /* on error return */
61         }
62     }
63     closedir(dir);
64     return 0;
65 }