Imported Upstream version 0.8.0.5
[psensor-pkg-ubuntu.git] / src / lib / pio.c
1 /*
2  * Copyright (C) 2010-2014 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 #define _LARGEFILE_SOURCE 1
20 #include "config.h"
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <sys/stat.h>
25 #include <string.h>
26 #include <dirent.h>
27
28 #include "pio.h"
29
30 static char *path_append(const char *dir, const char *path)
31 {
32         char *result;
33
34         result = malloc(strlen(dir) + 1 + strlen(path) + 1);
35
36         strcpy(result, dir);
37         strcat(result, "/");
38         strcat(result, path);
39
40         return result;
41 }
42
43 static char **paths_add(char **paths, int n, char *path)
44 {
45         char **result;
46
47         result = malloc((n+1) * sizeof(void *));
48
49         memcpy(result + 1, paths, n * sizeof(void *));
50
51         *result = path;
52
53         return result;
54 }
55
56 char **dir_list(const char *dpath, int (*filter) (const char *))
57 {
58         struct dirent *ent;
59         DIR *dir;
60         char **paths, *path, *name, **tmp;
61         int n;
62
63         dir = opendir(dpath);
64
65         if (!dir)
66                 return NULL;
67
68         n = 1;
69         paths = malloc(sizeof(void *));
70         *paths = NULL;
71
72         while ((ent = readdir(dir)) != NULL) {
73                 name = ent->d_name;
74
75                 if (!strcmp(name, ".") || !strcmp(name, ".."))
76                         continue;
77
78                 path = path_append(dpath, name);
79
80                 if (!filter || filter(path)) {
81                         tmp = paths_add(paths, n, path);
82                         free(paths);
83                         paths = tmp;
84
85                         n++;
86                 } else {
87                         free(path);
88                 }
89         }
90
91         closedir(dir);
92
93         return paths;
94 }
95
96 void paths_free(char **paths)
97 {
98         char **paths_cur;
99
100         paths_cur = paths;
101         while (*paths_cur) {
102                 free(*paths_cur);
103
104                 paths_cur++;
105         }
106
107         free(paths);
108 }