dirname.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include "dirname.h"
  2. #include <errno.h>
  3. #include <string.h>
  4. #include <sys/param.h>
  5. #include "strlcpy.h"
  6. char *
  7. dirname(const char *path)
  8. {
  9. static char bname[MAXPATHLEN] = "";
  10. register const char *endp = NULL;
  11. /* Empty or NULL string gets treated as "." */
  12. if (path == NULL || *path == '\0') {
  13. strlcpy(bname, ".", sizeof bname);
  14. return(bname);
  15. }
  16. /* Strip trailing slashes */
  17. endp = path + strlen(path) - 1;
  18. while (endp > path && *endp == '/')
  19. endp--;
  20. /* Find the start of the dir */
  21. while (endp > path && *endp != '/')
  22. endp--;
  23. /* Either the dir is "/" or there are no slashes */
  24. if (endp == path) {
  25. strlcpy(bname, *endp == '/' ? "/" : ".", sizeof bname);
  26. return(bname);
  27. } else {
  28. do {
  29. endp--;
  30. } while (endp > path && *endp == '/');
  31. }
  32. if (endp - path + 2 > (signed) sizeof(bname)) {
  33. errno = ENAMETOOLONG;
  34. return(NULL);
  35. }
  36. strlcpy(bname, path, endp - path + 2);
  37. return(bname);
  38. }