Home | History | Annotate | Download | only in e2p
      1 /*
      2  * iod.c		- Iterate a function on each entry of a directory
      3  *
      4  * Copyright (C) 1993, 1994  Remy Card <card (at) 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"
     18 #if HAVE_UNISTD_H
     19 #include <unistd.h>
     20 #endif
     21 #include <stdlib.h>
     22 #include <string.h>
     23 
     24 int iterate_on_dir (const char * dir_name,
     25 		    int (*func) (const char *, struct dirent *, void *),
     26 		    void * private)
     27 {
     28 	DIR * dir;
     29 	struct dirent *de, *dep;
     30 	int	max_len = -1, len;
     31 
     32 #if HAVE_PATHCONF && defined(_PC_NAME_MAX)
     33 	max_len = pathconf(dir_name, _PC_NAME_MAX);
     34 #endif
     35 	if (max_len == -1) {
     36 #ifdef _POSIX_NAME_MAX
     37 		max_len = _POSIX_NAME_MAX;
     38 #else
     39 #ifdef NAME_MAX
     40 		max_len = NAME_MAX;
     41 #else
     42 		max_len = 256;
     43 #endif /* NAME_MAX */
     44 #endif /* _POSIX_NAME_MAX */
     45 	}
     46 	max_len += sizeof(struct dirent);
     47 
     48 	de = malloc(max_len+1);
     49 	if (!de)
     50 		return -1;
     51 	memset(de, 0, max_len+1);
     52 
     53 	dir = opendir (dir_name);
     54 	if (dir == NULL) {
     55 		free(de);
     56 		return -1;
     57 	}
     58 	while ((dep = readdir (dir))) {
     59 		len = sizeof(struct dirent);
     60 #ifdef HAVE_RECLEN_DIRENT
     61 		if (len < dep->d_reclen)
     62 			len = dep->d_reclen;
     63 		if (len > max_len)
     64 			len = max_len;
     65 #endif
     66 		memcpy(de, dep, len);
     67 		(*func) (dir_name, de, private);
     68 	}
     69 	free(de);
     70 	closedir(dir);
     71 	return 0;
     72 }
     73