1 /*
2  * iod.c		- Iterate a function on each entry of a directory
3  *
4  * Copyright (C) 1993, 1994  Remy Card <card@masi.ibp.fr>
5  *                           Laboratoire MASI, Institut Blaise Pascal
6  *                           Universite Pierre et Marie Curie (Paris VI)
7  *
8  * %Begin-Header%
9  * This file may be redistributed under the terms of the GNU Library
10  * General Public License, version 2.
11  * %End-Header%
12  */
13 
14 /*
15  * History:
16  * 93/10/30	- Creation
17  */
18 
19 #include "e2p.h"
20 #if HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23 #include <stdlib.h>
24 #include <string.h>
25 
iterate_on_dir(const char * dir_name,int (* func)(const char *,struct dirent *,void *),void * private)26 int iterate_on_dir (const char * dir_name,
27 		    int (*func) (const char *, struct dirent *, void *),
28 		    void * private)
29 {
30 	DIR * dir;
31 	struct dirent *de, *dep;
32 	int	max_len = -1, len, ret = 0;
33 
34 #if HAVE_PATHCONF && defined(_PC_NAME_MAX)
35 	max_len = pathconf(dir_name, _PC_NAME_MAX);
36 #endif
37 	if (max_len == -1) {
38 #ifdef _POSIX_NAME_MAX
39 		max_len = _POSIX_NAME_MAX;
40 #else
41 #ifdef NAME_MAX
42 		max_len = NAME_MAX;
43 #else
44 		max_len = 256;
45 #endif /* NAME_MAX */
46 #endif /* _POSIX_NAME_MAX */
47 	}
48 	max_len += sizeof(struct dirent);
49 
50 	de = malloc(max_len+1);
51 	if (!de)
52 		return -1;
53 	memset(de, 0, max_len+1);
54 
55 	dir = opendir (dir_name);
56 	if (dir == NULL) {
57 		free(de);
58 		return -1;
59 	}
60 	while ((dep = readdir (dir))) {
61 #ifdef HAVE_RECLEN_DIRENT
62 		len = dep->d_reclen;
63 		if (len > max_len)
64 			len = max_len;
65 #else
66 		len = sizeof(struct dirent);
67 #endif
68 		memcpy(de, dep, len);
69 		if ((*func)(dir_name, de, private))
70 			ret++;
71 	}
72 	free(de);
73 	closedir(dir);
74 	return ret;
75 }
76