aboutsummaryrefslogtreecommitdiff
path: root/util-linux/e2p/iod.c
blob: 808d3a39d097ceffd6ad035ae0f3f7174fc3966f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
 * iod.c		- Iterate a function on each entry of a directory
 *
 * Copyright (C) 1993, 1994  Remy Card <card@masi.ibp.fr>
 *                           Laboratoire MASI, Institut Blaise Pascal
 *                           Universite Pierre et Marie Curie (Paris VI)
 *
 * This file can be redistributed under the terms of the GNU Library General
 * Public License
 */

/*
 * History:
 * 93/10/30	- Creation
 */

#include "e2p.h"
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#include <string.h>

int iterate_on_dir (const char * dir_name,
		    int (*func) (const char *, struct dirent *, void *),
		    void * private)
{
	DIR * dir;
	struct dirent *de, *dep;
	int	max_len = -1, len;

#if HAVE_PATHCONF && defined(_PC_NAME_MAX) 
	max_len = pathconf(dir_name, _PC_NAME_MAX);
#endif
	if (max_len == -1) {
#ifdef _POSIX_NAME_MAX
		max_len = _POSIX_NAME_MAX;
#else
#ifdef NAME_MAX
		max_len = NAME_MAX;
#else
		max_len = 256;
#endif /* NAME_MAX */
#endif /* _POSIX_NAME_MAX */
	}
	max_len += sizeof(struct dirent);

	de = malloc(max_len+1);
	if (!de)
		return -1;
	memset(de, 0, max_len+1);

	dir = opendir (dir_name);
	if (dir == NULL) {
		free(de);
		return -1;
	}
	while ((dep = readdir (dir))) {
		len = sizeof(struct dirent);
#ifdef HAVE_RECLEN_DIRENT
		if (len < dep->d_reclen)
			len = dep->d_reclen;
		if (len > max_len)
			len = max_len;
#endif
		memcpy(de, dep, len);
		(*func) (dir_name, de, private);
	}
	free(de);
	closedir(dir);
	return 0;
}