3
0

xreadlink.c 716 B

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