blob: 5321f2da1882e8ef850246afc2986375974d2258 [file] [log] [blame]
Mike Frysingerd89e6292005-04-24 05:07:59 +00001/*
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 * This file can be redistributed under the terms of the GNU Library General
9 * Public License
10 */
11
12/*
13 * History:
14 * 93/10/30 - Creation
15 */
16
17#include "e2p.h"
Mike Frysingerd89e6292005-04-24 05:07:59 +000018#include <unistd.h>
Mike Frysingerd89e6292005-04-24 05:07:59 +000019#include <stdlib.h>
20#include <string.h>
21
22int iterate_on_dir (const char * dir_name,
23 int (*func) (const char *, struct dirent *, void *),
24 void * private)
25{
26 DIR * dir;
27 struct dirent *de, *dep;
Mike Frysingera88d5222005-05-09 21:57:44 +000028 int max_len, len;
Mike Frysingerd89e6292005-04-24 05:07:59 +000029
Mike Frysingera88d5222005-05-09 21:57:44 +000030 max_len = PATH_MAX + sizeof(struct dirent);
31 de = (struct dirent *)xmalloc(max_len+1);
Mike Frysingerd89e6292005-04-24 05:07:59 +000032 memset(de, 0, max_len+1);
33
34 dir = opendir (dir_name);
35 if (dir == NULL) {
36 free(de);
37 return -1;
38 }
39 while ((dep = readdir (dir))) {
40 len = sizeof(struct dirent);
Mike Frysingerd89e6292005-04-24 05:07:59 +000041 if (len < dep->d_reclen)
42 len = dep->d_reclen;
43 if (len > max_len)
44 len = max_len;
Mike Frysingerd89e6292005-04-24 05:07:59 +000045 memcpy(de, dep, len);
46 (*func) (dir_name, de, private);
47 }
48 free(de);
49 closedir(dir);
50 return 0;
51}