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