3 * Copyright (C) 2002 Simone Piccardi
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.
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.
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.
19 /*****************************************************************************
21 * File dir_scan.c: routine for directory scan
23 * Author: S. Piccardi Jan. 2003
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 */
36 * Scan all entries in a directory, executing the provided function
39 * Input: the directory name and a computation function
40 * Return: 0 if OK, -1 on errors
42 int dir_scan(char * dirname, int(*compute)(struct dirent *))
45 struct dirent *direntry;
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 */
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 */