logo

cmd-glob

glob(1) wrapper around glob(3), inspired by https://github.com/isaacs/node-glob

glob.c (1486B)


  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 c = EOF;
  11. int flags = GLOB_NOSORT;
  12. /* flawfinder: ignore. Old implementations of getopt should fix themselves */
  13. while((c = getopt(argc, argv, "m")) != EOF)
  14. {
  15. switch(c)
  16. {
  17. case 'm': // mark
  18. flags |= GLOB_MARK;
  19. break;
  20. default:
  21. fprintf(stderr, "glob: Unhandled getopt case: %c\n", c);
  22. return 1;
  23. }
  24. }
  25. argc -= optind;
  26. argv += optind;
  27. if(argc == 0) {
  28. fprintf(stderr, "Usage: glob [-m] pattern ...\n");
  29. return 1;
  30. }
  31. for(int i = 0; i < argc; i++)
  32. {
  33. char *pat = argv[i];
  34. glob_t globbuf;
  35. int ret = glob(pat, flags, NULL, &globbuf);
  36. switch(ret)
  37. {
  38. case 0:
  39. break;
  40. case GLOB_ABORTED:
  41. fprintf(stderr, "glob: Scanned stopped, errfunc returned non-zero\n");
  42. continue;
  43. case GLOB_NOMATCH:
  44. //fprintf(stderr, "glob: Found no files matching pattern %s\n", pat);
  45. continue;
  46. case GLOB_NOSPACE:
  47. fprintf(stderr, "glob: Memory allocation error\n");
  48. return 1;
  49. default:
  50. fprintf(stderr, "glob: Unknown glob(3) return value %d\n", ret);
  51. return 1;
  52. }
  53. for(size_t pi = 0; pi < globbuf.gl_pathc; pi++)
  54. {
  55. printf("%s\n", globbuf.gl_pathv[pi]);
  56. }
  57. globfree(&globbuf);
  58. }
  59. }