3
0

xgetcwd.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * xgetcwd.c -- return current directory with unlimited length
  3. * Copyright (C) 1992, 1996 Free Software Foundation, Inc.
  4. * Written by David MacKenzie <djm@gnu.ai.mit.edu>.
  5. *
  6. * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru>
  7. */
  8. #include <stdlib.h>
  9. #include <errno.h>
  10. #include <unistd.h>
  11. #include <limits.h>
  12. #include <sys/param.h>
  13. #include "libbb.h"
  14. /* Amount to increase buffer size by in each try. */
  15. #define PATH_INCR 32
  16. /* Return the current directory, newly allocated, arbitrarily long.
  17. Return NULL and set errno on error.
  18. If argument is not NULL (previous usage allocate memory), call free()
  19. */
  20. char *
  21. xgetcwd (char *cwd)
  22. {
  23. char *ret;
  24. unsigned path_max;
  25. path_max = (unsigned) PATH_MAX;
  26. path_max += 2; /* The getcwd docs say to do this. */
  27. if(cwd==0)
  28. cwd = xmalloc (path_max);
  29. while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) {
  30. path_max += PATH_INCR;
  31. cwd = xrealloc (cwd, path_max);
  32. }
  33. if (ret == NULL) {
  34. free (cwd);
  35. bb_perror_msg("getcwd()");
  36. return NULL;
  37. }
  38. return cwd;
  39. }