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 "config.h" 20 #include "e2p.h" 21 #if HAVE_UNISTD_H 22 #include <unistd.h> 23 #endif 24 #include <stdlib.h> 25 #include <string.h> 26 27 int iterate_on_dir (const char * dir_name, 28 int (*func) (const char *, struct dirent *, void *), 29 void * private) 30 { 31 DIR * dir; 32 struct dirent *de, *dep; 33 int max_len = -1, len, ret = 0; 34 35 #if HAVE_PATHCONF && defined(_PC_NAME_MAX) 36 max_len = pathconf(dir_name, _PC_NAME_MAX); 37 #endif 38 if (max_len == -1) { 39 #ifdef _POSIX_NAME_MAX 40 max_len = _POSIX_NAME_MAX; 41 #else 42 #ifdef NAME_MAX 43 max_len = NAME_MAX; 44 #else 45 max_len = 256; 46 #endif /* NAME_MAX */ 47 #endif /* _POSIX_NAME_MAX */ 48 } 49 max_len += sizeof(struct dirent); 50 51 de = malloc(max_len+1); 52 if (!de) 53 return -1; 54 memset(de, 0, max_len+1); 55 56 dir = opendir (dir_name); 57 if (dir == NULL) { 58 free(de); 59 return -1; 60 } 61 while ((dep = readdir (dir))) { 62 #ifdef HAVE_RECLEN_DIRENT 63 len = dep->d_reclen; 64 if (len > max_len) 65 len = max_len; 66 #else 67 len = sizeof(struct dirent); 68 #endif 69 memcpy(de, dep, len); 70 if ((*func)(dir_name, de, private)) 71 ret++; 72 } 73 free(de); 74 closedir(dir); 75 return ret; 76 }