/contrib/cvs/lib/xgetwd.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 67 lines · 39 code · 12 blank · 16 comment · 6 complexity · 1773cc33c18ebc1534251994bb32c39a MD5 · raw file

  1. /* xgetwd.c -- return current directory with unlimited length
  2. Copyright (C) 1992, 1997 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details. */
  11. /* Derived from xgetcwd.c in e.g. the GNU sh-utils. */
  12. #ifdef HAVE_CONFIG_H
  13. #include <config.h>
  14. #endif
  15. #include "system.h"
  16. #include <stdio.h>
  17. #include <errno.h>
  18. #ifndef errno
  19. extern int errno;
  20. #endif
  21. #include <sys/types.h>
  22. /* Amount by which to increase buffer size when allocating more space. */
  23. #define PATH_INCR 32
  24. char *xmalloc ();
  25. char *xrealloc ();
  26. /* Return the current directory, newly allocated, arbitrarily long.
  27. Return NULL and set errno on error. */
  28. char *
  29. xgetwd ()
  30. {
  31. char *cwd;
  32. char *ret;
  33. unsigned path_max;
  34. errno = 0;
  35. path_max = (unsigned) PATH_MAX;
  36. path_max += 2; /* The getcwd docs say to do this. */
  37. cwd = xmalloc (path_max);
  38. errno = 0;
  39. while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE)
  40. {
  41. path_max += PATH_INCR;
  42. cwd = xrealloc (cwd, path_max);
  43. errno = 0;
  44. }
  45. if (ret == NULL)
  46. {
  47. int save_errno = errno;
  48. free (cwd);
  49. errno = save_errno;
  50. return NULL;
  51. }
  52. return cwd;
  53. }