3
0

xgetcwd.c 1023 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * xgetcwd.c -- return current directory with unlimited length
  4. * Copyright (C) 1992, 1996 Free Software Foundation, Inc.
  5. * Written by David MacKenzie <djm@gnu.ai.mit.edu>.
  6. *
  7. * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru>
  8. *
  9. * Licensed under GPLv2, see file LICENSE in this tarball for details.
  10. */
  11. #include "libbb.h"
  12. /* Return the current directory, newly allocated, arbitrarily long.
  13. Return NULL and set errno on error.
  14. If argument is not NULL (previous usage allocate memory), call free()
  15. */
  16. char* FAST_FUNC
  17. xrealloc_getcwd_or_warn(char *cwd)
  18. {
  19. #define PATH_INCR 64
  20. char *ret;
  21. unsigned path_max;
  22. path_max = 128; /* 128 + 64 should be enough for 99% of cases */
  23. while (1) {
  24. path_max += PATH_INCR;
  25. cwd = xrealloc(cwd, path_max);
  26. ret = getcwd(cwd, path_max);
  27. if (ret == NULL) {
  28. if (errno == ERANGE)
  29. continue;
  30. free(cwd);
  31. bb_perror_msg("getcwd");
  32. return NULL;
  33. }
  34. cwd = xrealloc(cwd, strlen(cwd) + 1);
  35. return cwd;
  36. }
  37. }