xgetcwd.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* xgetcwd.c -- return current directory with unlimited length
  2. Copyright (C) 1992, 1996, 2000, 2001 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. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software Foundation,
  13. Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  14. /* Written by David MacKenzie <[email protected]>. */
  15. #if HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. #include <stdio.h>
  19. #include <errno.h>
  20. #ifndef errno
  21. extern int errno;
  22. #endif
  23. #include <sys/types.h>
  24. #if HAVE_STDLIB_H
  25. # include <stdlib.h>
  26. #endif
  27. #if HAVE_UNISTD_H
  28. # include <unistd.h>
  29. #endif
  30. #if HAVE_GETCWD
  31. char *getcwd ();
  32. #else
  33. char *getwd ();
  34. # define getcwd(Buf, Max) getwd (Buf)
  35. #endif
  36. #include "xalloc.h"
  37. /* Return the current directory, newly allocated, arbitrarily long.
  38. Return NULL and set errno on error. */
  39. char *
  40. xgetcwd ()
  41. {
  42. #if defined __GLIBC__ && __GLIBC__ >= 2
  43. return getcwd (NULL, 0);
  44. #else
  45. size_t buf_size = 128; /* must be a power of 2 */
  46. char *buf = NULL;
  47. while (1)
  48. {
  49. char *cwd;
  50. buf = (char *) xrealloc (buf, buf_size);
  51. cwd = getcwd (buf, buf_size);
  52. if (cwd != NULL)
  53. return cwd;
  54. if (errno != ERANGE)
  55. {
  56. free (buf);
  57. return NULL;
  58. }
  59. buf_size *= 2;
  60. if (buf_size == 0)
  61. xalloc_die ();
  62. }
  63. #endif
  64. }