xgetcwd.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. char *ret;
  46. size_t path_max;
  47. char buf[1024];
  48. errno = 0;
  49. ret = getcwd (buf, sizeof (buf));
  50. if (ret != NULL)
  51. return xstrdup (buf);
  52. if (errno != ERANGE)
  53. return NULL;
  54. path_max = 1 << 10;
  55. for (;;)
  56. {
  57. char *cwd = (char *) xmalloc (path_max);
  58. int save_errno;
  59. errno = 0;
  60. ret = getcwd (cwd, path_max);
  61. if (ret != NULL)
  62. return ret;
  63. save_errno = errno;
  64. free (cwd);
  65. if (save_errno != ERANGE)
  66. {
  67. errno = save_errno;
  68. return NULL;
  69. }
  70. path_max *= 2;
  71. if (path_max == 0)
  72. xalloc_die ();
  73. }
  74. #endif
  75. }