basename.c (1161B)
- // Collection of Unix tools, comparable to coreutils
- // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
- #include <assert.h> // assert()
- #include <libgen.h> // basename()
- #include <stdio.h> // fprintf(), puts(), perror()
- #include <string.h> // strlen(), strncmp()
- static char *
- suffix_basename(char *name, char *suffix)
- {
- assert(name);
- assert(suffix);
- char *string = basename(name);
- size_t suflen = suffix ? strlen(suffix) : 0;
- size_t len = strlen(string);
- if(suflen < len && strcmp(&string[len - suflen], suffix) == 0)
- {
- string[len - suflen] = '\0';
- }
- return string;
- }
- int
- main(int argc, char *argv[])
- {
- int ret = 0;
- if((argc > 1) && (strncmp(argv[1], "--", 3) == 0))
- {
- argv++;
- argc--;
- }
- switch(argc)
- {
- case 1:
- ret = printf(".\n");
- break;
- case 2:
- ret = puts(basename(argv[1]));
- break;
- case 3:
- ret = puts(suffix_basename(argv[1], argv[2]));
- break;
- default:
- fprintf(stderr, "usage: basename string [suffix]\n");
- return 1;
- }
- if(ret < 0)
- {
- perror("basename: puts");
- return 1;
- }
- else
- {
- return 0;
- }
- }