2.82 xs_glob.h
 1/* copyright (c) 2022 - 2025 grunfink et al. / MIT license */
 2
 3#ifndef _XS_GLOB_H
 4
 5#define _XS_GLOB_H
 6
 7xs_list *xs_glob_n(const char *spec, int basename, int reverse, int mark, int max);
 8#define xs_glob(spec, basename, reverse) xs_glob_n(spec, basename, reverse, 0, XS_ALL)
 9#define xs_glob_m(spec, basename, reverse) xs_glob_n(spec, basename, reverse, 1, XS_ALL)
10
11
12#ifdef XS_IMPLEMENTATION
13
14#include <glob.h>
15
16xs_list *xs_glob_n(const char *spec, int basename, int reverse, int mark, int max)
17/* does a globbing and returns the found files */
18{
19    glob_t globbuf;
20    xs_list *list = xs_list_new();
21
22    if (glob(spec, mark ? GLOB_MARK : 0, NULL, &globbuf) == 0) {
23        int n;
24
25        if (max > (int) globbuf.gl_pathc)
26            max = globbuf.gl_pathc;
27
28        for (n = 0; n < max; n++) {
29            char *p;
30
31            if (reverse)
32                p = globbuf.gl_pathv[globbuf.gl_pathc - n - 1];
33            else
34                p = globbuf.gl_pathv[n];
35
36            if (p != NULL) {
37                if (basename) {
38                    if ((p = strrchr(p, '/')) == NULL)
39                        continue;
40
41                    p++;
42                }
43
44                list = xs_list_append(list, p);
45            }
46        }
47    }
48
49    globfree(&globbuf);
50
51    return list;
52}
53
54
55#endif /* XS_IMPLEMENTATION */
56
57#endif /* _XS_GLOB_H */