xs_glob.h 1.3 KB

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