dirname.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. 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. }
  39. /* vim: set sts=2 sw=2 ts=8 et: */