logo

cmd-glob

glob(1) wrapper around glob(3), inspired by https://github.com/isaacs/node-glob git clone https://anongit.hacktivis.me/git/cmd-glob.git/

glob.c (1400B)


  1. // glob(1) wrapper around glob(3), inspired by https://github.com/isaacs/node-glob
  2. // SPDX-FileCopyrightText: 2023 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #include <getopt.h> // getopt, opt*
  5. #include <glob.h> // glob, GLOB
  6. #include <stdio.h> // fprintf
  7. int
  8. main(int argc, char *argv[])
  9. {
  10. int flags = GLOB_NOSORT;
  11. for(int c = -1; (c = getopt(argc, argv, "m")) != -1;)
  12. {
  13. switch(c)
  14. {
  15. case 'm': // mark
  16. flags |= GLOB_MARK;
  17. break;
  18. default:
  19. fprintf(stderr, "glob: Unhandled getopt case: %c\n", c);
  20. return 1;
  21. }
  22. }
  23. argc -= optind;
  24. argv += optind;
  25. if(argc == 0)
  26. {
  27. fprintf(stderr, "Usage: glob [-m] pattern ...\n");
  28. return 1;
  29. }
  30. for(int i = 0; i < argc; i++)
  31. {
  32. char *pat = argv[i];
  33. glob_t globbuf;
  34. int ret = glob(pat, flags, NULL, &globbuf);
  35. switch(ret)
  36. {
  37. case 0:
  38. break;
  39. case GLOB_ABORTED:
  40. fprintf(stderr, "glob: Scanned stopped, errfunc returned non-zero\n");
  41. continue;
  42. case GLOB_NOMATCH:
  43. //fprintf(stderr, "glob: Found no files matching pattern %s\n", pat);
  44. continue;
  45. case GLOB_NOSPACE:
  46. fprintf(stderr, "glob: Memory allocation error\n");
  47. return 1;
  48. default:
  49. fprintf(stderr, "glob: Unknown glob(3) return value %d\n", ret);
  50. return 1;
  51. }
  52. for(size_t pi = 0; pi < globbuf.gl_pathc; pi++)
  53. {
  54. printf("%s\n", globbuf.gl_pathv[pi]);
  55. }
  56. globfree(&globbuf);
  57. }
  58. }