xgetcwd.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. #include "pathmax.h"
  25. #if HAVE_GETCWD
  26. char *getcwd ();
  27. #else
  28. char *getwd ();
  29. # define getcwd(Buf, Max) getwd (Buf)
  30. #endif
  31. extern void *xmalloc ();
  32. extern char *xstrdup ();
  33. extern void free ();
  34. /* Return the current directory, newly allocated, arbitrarily long.
  35. Return NULL and set errno on error. */
  36. char *
  37. xgetcwd ()
  38. {
  39. #if defined __GLIBC__ && __GLIBC__ >= 2
  40. return getcwd (NULL, 0);
  41. #else
  42. char *ret;
  43. unsigned path_max;
  44. char buf[1024];
  45. errno = 0;
  46. ret = getcwd (buf, sizeof (buf));
  47. if (ret != NULL)
  48. return xstrdup (buf);
  49. if (errno != ERANGE)
  50. return NULL;
  51. path_max = 1300;
  52. path_max += 2; /* The getcwd docs say to do this. */
  53. for (;;)
  54. {
  55. char *cwd = (char *) xmalloc (path_max);
  56. errno = 0;
  57. ret = getcwd (cwd, path_max);
  58. if (ret != NULL)
  59. return ret;
  60. if (errno != ERANGE)
  61. {
  62. int save_errno = errno;
  63. free (cwd);
  64. errno = save_errno;
  65. return NULL;
  66. }
  67. free (cwd);
  68. path_max += path_max / 16;
  69. path_max += 32;
  70. }
  71. #endif
  72. }