"Robert P. J. Day" | 63fc1a9 | 2006-07-02 19:47:05 +0000 | [diff] [blame] | 1 | /* vi: set sw=4 ts=4: */ |
Mike Frysinger | d89e629 | 2005-04-24 05:07:59 +0000 | [diff] [blame] | 2 | /* |
| 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 Frysinger | d89e629 | 2005-04-24 05:07:59 +0000 | [diff] [blame] | 19 | #include <unistd.h> |
Mike Frysinger | d89e629 | 2005-04-24 05:07:59 +0000 | [diff] [blame] | 20 | #include <stdlib.h> |
| 21 | #include <string.h> |
| 22 | |
| 23 | int 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 Frysinger | a88d522 | 2005-05-09 21:57:44 +0000 | [diff] [blame] | 29 | int max_len, len; |
Mike Frysinger | d89e629 | 2005-04-24 05:07:59 +0000 | [diff] [blame] | 30 | |
Mike Frysinger | a88d522 | 2005-05-09 21:57:44 +0000 | [diff] [blame] | 31 | max_len = PATH_MAX + sizeof(struct dirent); |
| 32 | de = (struct dirent *)xmalloc(max_len+1); |
Mike Frysinger | d89e629 | 2005-04-24 05:07:59 +0000 | [diff] [blame] | 33 | 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 Frysinger | d89e629 | 2005-04-24 05:07:59 +0000 | [diff] [blame] | 42 | if (len < dep->d_reclen) |
| 43 | len = dep->d_reclen; |
| 44 | if (len > max_len) |
| 45 | len = max_len; |
Mike Frysinger | d89e629 | 2005-04-24 05:07:59 +0000 | [diff] [blame] | 46 | memcpy(de, dep, len); |
| 47 | (*func) (dir_name, de, private); |
| 48 | } |
| 49 | free(de); |
| 50 | closedir(dir); |
| 51 | return 0; |
| 52 | } |