logo

utils

~/.local/bin tools and git-hooks git clone https://hacktivis.me/git/utils.git

basename.c (1161B)


  1. // Collection of Unix tools, comparable to coreutils
  2. // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
  4. #include <assert.h> // assert()
  5. #include <libgen.h> // basename()
  6. #include <stdio.h> // fprintf(), puts(), perror()
  7. #include <string.h> // strlen(), strncmp()
  8. static char *
  9. suffix_basename(char *name, char *suffix)
  10. {
  11. assert(name);
  12. assert(suffix);
  13. char *string = basename(name);
  14. size_t suflen = suffix ? strlen(suffix) : 0;
  15. size_t len = strlen(string);
  16. if(suflen < len && strcmp(&string[len - suflen], suffix) == 0)
  17. {
  18. string[len - suflen] = '\0';
  19. }
  20. return string;
  21. }
  22. int
  23. main(int argc, char *argv[])
  24. {
  25. int ret = 0;
  26. if((argc > 1) && (strncmp(argv[1], "--", 3) == 0))
  27. {
  28. argv++;
  29. argc--;
  30. }
  31. switch(argc)
  32. {
  33. case 1:
  34. ret = printf(".\n");
  35. break;
  36. case 2:
  37. ret = puts(basename(argv[1]));
  38. break;
  39. case 3:
  40. ret = puts(suffix_basename(argv[1], argv[2]));
  41. break;
  42. default:
  43. fprintf(stderr, "usage: basename string [suffix]\n");
  44. return 1;
  45. }
  46. if(ret < 0)
  47. {
  48. perror("basename: puts");
  49. return 1;
  50. }
  51. else
  52. {
  53. return 0;
  54. }
  55. }