xreadlink.c 691 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /*
  2. * xreadlink.c - safe implementation of readlink.
  3. * Returns a NULL on failure...
  4. */
  5. #include <stdio.h>
  6. /*
  7. * NOTE: This function returns a malloced char* that you will have to free
  8. * yourself. You have been warned.
  9. */
  10. #include <unistd.h>
  11. #include "libbb.h"
  12. char *xreadlink(const char *path)
  13. {
  14. enum { GROWBY = 80 }; /* how large we will grow strings by */
  15. char *buf = NULL;
  16. int bufsize = 0, readsize = 0;
  17. do {
  18. buf = xrealloc(buf, bufsize += GROWBY);
  19. readsize = readlink(path, buf, bufsize); /* 1st try */
  20. if (readsize == -1) {
  21. bb_perror_msg("%s", path);
  22. free(buf);
  23. return NULL;
  24. }
  25. }
  26. while (bufsize < readsize + 1);
  27. buf[readsize] = '\0';
  28. return buf;
  29. }