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