X-Git-Url: https://git.wpitchoune.net/gitweb/?a=blobdiff_plain;f=src%2Flib%2Fpio.c;h=ab2a9503895b709d565605df2783ebf5c638b195;hb=2b51051578ef29b031d0927388c4d62baa3c525e;hp=54d9efbb03b3cb01d303f8d9e058ebeb0416669f;hpb=a3c71b73815825dcd686f30a3b0012c169dab6d6;p=psensor.git diff --git a/src/lib/pio.c b/src/lib/pio.c index 54d9efb..ab2a950 100644 --- a/src/lib/pio.c +++ b/src/lib/pio.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 jeanfi@gmail.com + * Copyright (C) 2010-2012 jeanfi@gmail.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -24,11 +24,37 @@ #include "pio.h" -char **dir_list(const char *dpath, int (*filter) (const char *path)) +static char *path_append(const char *dir, const char *path) +{ + char *result; + + result = malloc(strlen(dir) + 1 + strlen(path) + 1); + + strcpy(result, dir); + strcat(result, "/"); + strcat(result, path); + + return result; +} + +static char **paths_add(char **paths, int n, char *path) +{ + char **result; + + result = malloc((n+1) * sizeof(void *)); + + memcpy(result + 1, paths, n * sizeof(void *)); + + *result = path; + + return result; +} + +char **dir_list(const char *dpath, int (*filter) (const char *)) { struct dirent *ent; DIR *dir; - char **paths; + char **paths, *path, *name, **tmp; int n; dir = opendir(dpath); @@ -41,30 +67,21 @@ char **dir_list(const char *dpath, int (*filter) (const char *path)) *paths = NULL; while ((ent = readdir(dir)) != NULL) { - char *fpath; - char *name = ent->d_name; + name = ent->d_name; if (!strcmp(name, ".") || !strcmp(name, "..")) continue; - fpath = malloc(strlen(dpath) + 1 + strlen(name) + 1); - - strcpy(fpath, dpath); - strcat(fpath, "/"); - strcat(fpath, name); + path = path_append(dpath, name); - if (!filter || filter(fpath)) { - char **npaths; - - n++; - npaths = malloc(n * sizeof(void *)); - memcpy(npaths + 1, paths, (n - 1) * sizeof(void *)); + if (!filter || filter(path)) { + tmp = paths_add(paths, n, path); free(paths); - paths = npaths; - *npaths = fpath; + paths = tmp; + n++; } else { - free(fpath); + free(path); } } @@ -86,4 +103,3 @@ void paths_free(char **paths) free(paths); } -