dirname.c 539 B

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