basename.c 734 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. void
  5. main(int argc, char **argv)
  6. {
  7. char *f, *b, *s;
  8. int n;
  9. if(argc < 2 || argc > 3){
  10. fprintf(stderr, "Usage: basename string [suffix]\n");
  11. exit(1);
  12. }
  13. s = argv[1];
  14. b = s + strlen(s) - 1;
  15. while(b > s && *b == '/')
  16. b--;
  17. *++b = 0;
  18. if(b == s+1 && s[0] == '/') {
  19. printf("/");
  20. exit(0);
  21. }
  22. /* now b is after last char of string, trailing slashes removed */
  23. for(f = b; f >= s; f--)
  24. if(*f == '/'){
  25. f++;
  26. break;
  27. }
  28. if(f < s)
  29. f = s;
  30. /* now f is first char after last remaining slash, or first char */
  31. if(argc == 3){
  32. n = strlen(argv[2]);
  33. if(n < b-f && strncmp(b-n, argv[2], n) == 0){
  34. b -= n;
  35. *b = 0;
  36. }
  37. }
  38. printf("%s\n", f);
  39. exit(0);
  40. }