glob.c (1486B)
- // glob(1) wrapper around glob(3), inspired by https://github.com/isaacs/node-glob
- // SPDX-FileCopyrightText: 2023 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #include <getopt.h> // getopt, opt*
- #include <glob.h> // glob, GLOB
- #include <stdio.h> // fprintf
- int
- main(int argc, char *argv[])
- {
- int c = EOF;
- int flags = GLOB_NOSORT;
- /* flawfinder: ignore. Old implementations of getopt should fix themselves */
- while((c = getopt(argc, argv, "m")) != EOF)
- {
- switch(c)
- {
- case 'm': // mark
- flags |= GLOB_MARK;
- break;
- default:
- fprintf(stderr, "glob: Unhandled getopt case: %c\n", c);
- return 1;
- }
- }
- argc -= optind;
- argv += optind;
- if(argc == 0) {
- fprintf(stderr, "Usage: glob [-m] pattern ...\n");
- return 1;
- }
- for(int i = 0; i < argc; i++)
- {
- char *pat = argv[i];
- glob_t globbuf;
- int ret = glob(pat, flags, NULL, &globbuf);
- switch(ret)
- {
- case 0:
- break;
- case GLOB_ABORTED:
- fprintf(stderr, "glob: Scanned stopped, errfunc returned non-zero\n");
- continue;
- case GLOB_NOMATCH:
- //fprintf(stderr, "glob: Found no files matching pattern %s\n", pat);
- continue;
- case GLOB_NOSPACE:
- fprintf(stderr, "glob: Memory allocation error\n");
- return 1;
- default:
- fprintf(stderr, "glob: Unknown glob(3) return value %d\n", ret);
- return 1;
- }
- for(size_t pi = 0; pi < globbuf.gl_pathc; pi++)
- {
- printf("%s\n", globbuf.gl_pathv[pi]);
- }
- globfree(&globbuf);
- }
- }