xs_glob.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 max);
  5. #define xs_glob(spec, basename, reverse) xs_glob_n(spec, basename, reverse, XS_ALL)
  6. #ifdef XS_IMPLEMENTATION
  7. #include <glob.h>
  8. xs_list *xs_glob_n(const char *spec, int basename, int reverse, int max)
  9. /* does a globbing and returns the found files */
  10. {
  11. glob_t globbuf;
  12. xs_list *list = xs_list_new();
  13. if (glob(spec, 0, NULL, &globbuf) == 0) {
  14. int n;
  15. if (max > (int) globbuf.gl_pathc)
  16. max = globbuf.gl_pathc;
  17. for (n = 0; n < max; n++) {
  18. char *p;
  19. if (reverse)
  20. p = globbuf.gl_pathv[globbuf.gl_pathc - n - 1];
  21. else
  22. p = globbuf.gl_pathv[n];
  23. if (p != NULL) {
  24. if (basename) {
  25. if ((p = strrchr(p, '/')) == NULL)
  26. continue;
  27. p++;
  28. }
  29. list = xs_list_append(list, p);
  30. }
  31. }
  32. }
  33. globfree(&globbuf);
  34. return list;
  35. }
  36. #endif /* XS_IMPLEMENTATION */
  37. #endif /* _XS_GLOB_H */