basename.c 886 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2018 K. Lange
  5. *
  6. * basename - print file name
  7. */
  8. #include <stdio.h>
  9. #include <string.h>
  10. int main(int argc, char * argv[]) {
  11. if (argc < 2) {
  12. fprintf(stderr, "%s: expected argument\n", argv[0]);
  13. return 1;
  14. }
  15. char * s = argv[1];
  16. char * c = NULL;
  17. do {
  18. while (*s == '/') {
  19. *s = '\0'; s++;
  20. if (!*s) goto _done;
  21. }
  22. c = s;
  23. s = strchr(c,'/');
  24. } while (s);
  25. _done:
  26. if (!c) {
  27. /* Special case */
  28. fprintf(stdout, "/\n");
  29. return 0;
  30. }
  31. if (argc > 2) {
  32. char * suffix = argv[2];
  33. char * found = strstr(c + strlen(c) - strlen(suffix), suffix);
  34. if (found && (found - c == (int)(strlen(c)-strlen(suffix)))) {
  35. *found = '\0';
  36. }
  37. }
  38. fprintf(stdout, "%s\n", c);
  39. return 0;
  40. }