1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2013 Index Data
3 * See the file LICENSE for details.
7 \brief File globbing (ala POSIX glob, but simpler)
13 #include <sys/types.h>
19 #include <yaz/wrbuf.h>
20 #include <yaz/tpath.h>
22 #include <yaz/dirent.h>
24 #include <yaz/file_glob.h>
25 #include <yaz/match_glob.h>
28 struct res_entry *next;
34 size_t number_of_entries;
35 struct res_entry **last_entry;
36 struct res_entry *entries;
39 static void glob_r(yaz_glob_res_t res, const char *pattern, size_t off,
42 size_t prefix_len = strlen(prefix);
45 while (pattern[i] && !strchr("/\\", pattern[i]))
47 if (strchr("?*", pattern[i]))
52 if (!is_pattern && pattern[i]) /* no pattern and directory part */
54 i++; /* skip dir sep */
55 memcpy(prefix + prefix_len, pattern + off, i - off);
56 prefix[prefix_len + i - off] = '\0';
57 glob_r(res, pattern, i, prefix);
58 prefix[prefix_len] = '\0';
62 DIR * dir = opendir(*prefix ? prefix : "." );
68 while ((ent = readdir(dir)))
71 memcpy(prefix + prefix_len, pattern + off, i - off);
72 prefix[prefix_len + i - off] = '\0';
73 r = yaz_match_glob(prefix + prefix_len, ent->d_name);
74 prefix[prefix_len] = '\0';
78 strcpy(prefix + prefix_len, ent->d_name);
81 glob_r(res, pattern, i, prefix);
85 struct res_entry *ent =
86 nmem_malloc(res->nmem, sizeof(*ent));
87 ent->file = nmem_strdup(res->nmem, prefix);
89 *res->last_entry = ent;
90 res->last_entry = &ent->next;
91 res->number_of_entries++;
93 prefix[prefix_len] = '\0';
101 static int cmp_entry(const void *a, const void *b)
103 struct res_entry *ent_a = *(struct res_entry **) a;
104 struct res_entry *ent_b = *(struct res_entry **) b;
105 return strcmp(ent_a->file, ent_b->file);
108 static void sort_them(yaz_glob_res_t res)
111 struct res_entry **ent_p;
112 struct res_entry **ent = nmem_malloc(res->nmem, sizeof(*ent) * res->number_of_entries);
113 struct res_entry *ent_i = res->entries;
114 for (i = 0; i < res->number_of_entries; i++)
119 qsort(ent, res->number_of_entries, sizeof(*ent), cmp_entry);
120 ent_p = &res->entries;
121 for (i = 0; i < res->number_of_entries; i++)
124 ent_p = &ent[i]->next;
129 int yaz_file_glob(const char *pattern, yaz_glob_res_t *res)
131 char prefix[FILENAME_MAX+1];
132 NMEM nmem = nmem_create();
135 *res = nmem_malloc(nmem, sizeof(**res));
136 (*res)->number_of_entries = 0;
139 (*res)->last_entry = &(*res)->entries;
140 glob_r(*res, pattern, 0, prefix);
145 void yaz_file_globfree(yaz_glob_res_t *res)
149 /* must free entries as well */
150 nmem_destroy((*res)->nmem);
155 const char *yaz_file_glob_get_file(yaz_glob_res_t res, size_t idx)
157 struct res_entry *ent = res->entries;
168 size_t yaz_file_glob_get_num(yaz_glob_res_t res)
170 return res->number_of_entries;
176 * c-file-style: "Stroustrup"
177 * indent-tabs-mode: nil
179 * vim: shiftwidth=4 tabstop=8 expandtab