xgetcwd.c 948 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. #include "libbb.h"
  10. /* Return the current directory, newly allocated, arbitrarily long.
  11. Return NULL and set errno on error.
  12. If argument is not NULL (previous usage allocate memory), call free()
  13. */
  14. char* FAST_FUNC
  15. xrealloc_getcwd_or_warn(char *cwd)
  16. {
  17. #define PATH_INCR 64
  18. char *ret;
  19. unsigned path_max;
  20. path_max = 128; /* 128 + 64 should be enough for 99% of cases */
  21. while (1) {
  22. path_max += PATH_INCR;
  23. cwd = xrealloc(cwd, path_max);
  24. ret = getcwd(cwd, path_max);
  25. if (ret == NULL) {
  26. if (errno == ERANGE)
  27. continue;
  28. free(cwd);
  29. bb_perror_msg("getcwd");
  30. return NULL;
  31. }
  32. cwd = xrealloc(cwd, strlen(cwd) + 1);
  33. return cwd;
  34. }
  35. }