dirname.c 1.2 KB

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