xgetcwd.c 995 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. /* Amount to increase buffer size by in each try. */
  11. #define PATH_INCR 32
  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 *
  17. xgetcwd(char *cwd)
  18. {
  19. char *ret;
  20. unsigned path_max;
  21. path_max = (unsigned) PATH_MAX;
  22. path_max += 2; /* The getcwd docs say to do this. */
  23. if (cwd==0)
  24. cwd = xmalloc(path_max);
  25. while ((ret = getcwd(cwd, path_max)) == NULL && errno == ERANGE) {
  26. path_max += PATH_INCR;
  27. cwd = xrealloc(cwd, path_max);
  28. }
  29. if (ret == NULL) {
  30. free(cwd);
  31. bb_perror_msg("getcwd");
  32. return NULL;
  33. }
  34. return cwd;
  35. }