blob: 8d4c5cdcb9d86eb323aa6c08d1591e4ea785a175 [file] [log] [blame]
"Robert P. J. Day"63fc1a92006-07-02 19:47:05 +00001/* vi: set sw=4 ts=4: */
Mike Frysingerd89e6292005-04-24 05:07:59 +00002/*
3 * iod.c - Iterate a function on each entry of a directory
4 *
5 * Copyright (C) 1993, 1994 Remy Card <card@masi.ibp.fr>
6 * Laboratoire MASI, Institut Blaise Pascal
7 * Universite Pierre et Marie Curie (Paris VI)
8 *
9 * This file can be redistributed under the terms of the GNU Library General
10 * Public License
11 */
12
13/*
14 * History:
15 * 93/10/30 - Creation
16 */
17
18#include "e2p.h"
Mike Frysingerd89e6292005-04-24 05:07:59 +000019#include <unistd.h>
Mike Frysingerd89e6292005-04-24 05:07:59 +000020#include <stdlib.h>
21#include <string.h>
22
23int iterate_on_dir (const char * dir_name,
24 int (*func) (const char *, struct dirent *, void *),
25 void * private)
26{
27 DIR * dir;
28 struct dirent *de, *dep;
Mike Frysingera88d5222005-05-09 21:57:44 +000029 int max_len, len;
Mike Frysingerd89e6292005-04-24 05:07:59 +000030
Mike Frysingera88d5222005-05-09 21:57:44 +000031 max_len = PATH_MAX + sizeof(struct dirent);
32 de = (struct dirent *)xmalloc(max_len+1);
Mike Frysingerd89e6292005-04-24 05:07:59 +000033 memset(de, 0, max_len+1);
34
35 dir = opendir (dir_name);
36 if (dir == NULL) {
37 free(de);
38 return -1;
39 }
40 while ((dep = readdir (dir))) {
41 len = sizeof(struct dirent);
Mike Frysingerd89e6292005-04-24 05:07:59 +000042 if (len < dep->d_reclen)
43 len = dep->d_reclen;
44 if (len > max_len)
45 len = max_len;
Mike Frysingerd89e6292005-04-24 05:07:59 +000046 memcpy(de, dep, len);
47 (*func) (dir_name, de, private);
48 }
49 free(de);
50 closedir(dir);
51 return 0;
52}