updated copyright to 2013
[psensor.git] / src / lib / pio.c
1 /*
2  * Copyright (C) 2010-2013 jeanfi@gmail.com
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301 USA
18  */
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <sys/stat.h>
22 #include <string.h>
23 #include <dirent.h>
24
25 #include "pio.h"
26
27 static char *path_append(const char *dir, const char *path)
28 {
29         char *result;
30
31         result = malloc(strlen(dir) + 1 + strlen(path) + 1);
32
33         strcpy(result, dir);
34         strcat(result, "/");
35         strcat(result, path);
36
37         return result;
38 }
39
40 static char **paths_add(char **paths, int n, char *path)
41 {
42         char **result;
43
44         result = malloc((n+1) * sizeof(void *));
45
46         memcpy(result + 1, paths, n * sizeof(void *));
47
48         *result = path;
49
50         return result;
51 }
52
53 char **dir_list(const char *dpath, int (*filter) (const char *))
54 {
55         struct dirent *ent;
56         DIR *dir;
57         char **paths, *path, *name, **tmp;
58         int n;
59
60         dir = opendir(dpath);
61
62         if (!dir)
63                 return NULL;
64
65         n = 1;
66         paths = malloc(sizeof(void *));
67         *paths = NULL;
68
69         while ((ent = readdir(dir)) != NULL) {
70                 name = ent->d_name;
71
72                 if (!strcmp(name, ".") || !strcmp(name, ".."))
73                         continue;
74
75                 path = path_append(dpath, name);
76
77                 if (!filter || filter(path)) {
78                         tmp = paths_add(paths, n, path);
79                         free(paths);
80                         paths = tmp;
81
82                         n++;
83                 } else {
84                         free(path);
85                 }
86         }
87
88         closedir(dir);
89
90         return paths;
91 }
92
93 void paths_free(char **paths)
94 {
95         char **paths_cur;
96
97         paths_cur = paths;
98         while (*paths_cur) {
99                 free(*paths_cur);
100
101                 paths_cur++;
102         }
103
104         free(paths);
105 }