basename.c 729 B

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