2 * Copyright (C) 2003-2010 Neverball authors
4 * NEVERBALL is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published
6 * by the Free Software Foundation; either version 2 of the License,
7 * or (at your option) any later version.
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.
24 static char **get_dir_list(const char *path)
31 * HACK: MinGW provides numerous POSIX extensions to MSVCRT,
32 * including dirent.h, so parasti ever so lazily has not bothered
33 * to port the code below to FindFirstFile et al.
36 if ((dir = opendir(path)))
40 files = malloc(sizeof (char *));
42 while ((ent = readdir(dir)))
44 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
47 files[count++] = strdup(ent->d_name);
48 files = realloc(files, (count + 1) * sizeof (char *));
59 static void free_dir_list(void *files)
65 /* Free file names. */
66 for (file = files; *file; free(*file++));
68 /* Free trailing NULL. */
71 /* Free pointer list. */
76 static struct dir_item *add_item(Array items, const char *dir, const char *name)
78 struct dir_item *item = array_add(items);
80 item->path = *dir ? concat_string(dir, "/", name, NULL) : strdup(name);
86 static void del_item(Array items)
88 struct dir_item *item = array_get(items, array_len(items) - 1);
90 free((void *) item->path);
96 Array dir_scan(const char *path,
97 int (*filter) (struct dir_item *),
98 char **(*get_list) (const char *),
99 void (*free_list)(void *))
104 assert((get_list && free_list) || (!get_list && !free_list));
107 get_list = get_dir_list;
110 free_list = free_dir_list;
112 if ((list = get_list(path)))
116 items = array_new(sizeof (struct dir_item));
120 struct dir_item *item;
122 item = add_item(items, path, *file);
124 if (filter && !filter(item))
136 void dir_free(Array items)
138 while (array_len(items))