home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / fileutils-3.6 / lib / xgetcwd.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-11-23  |  1.8 KB  |  75 lines

  1. /* xgetcwd.c -- return current directory with unlimited length
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by David MacKenzie, djm@gnu.ai.mit.edu. */
  19.  
  20. #include <stdio.h>
  21. #include <errno.h>
  22. #ifndef errno
  23. extern int errno;
  24. #endif
  25. #include <sys/types.h>
  26. #include "pathmax.h"
  27.  
  28. #if !defined(_POSIX_VERSION) && !defined(HAVE_GETCWD)
  29. char *getwd ();
  30. #define getcwd(buf, max) getwd (buf)
  31. #else
  32. char *getcwd ();
  33. #endif
  34.  
  35. /* Amount to increase buffer size by in each try. */
  36. #define PATH_INCR 32
  37.  
  38. char *xmalloc ();
  39. char *xrealloc ();
  40. void free ();
  41.  
  42. /* Return the current directory, newly allocated, arbitrarily long.
  43.    Return NULL and set errno on error. */
  44.  
  45. char *
  46. xgetcwd ()
  47. {
  48.   char *cwd;
  49.   char *ret;
  50.   unsigned path_max;
  51.  
  52.   errno = 0;
  53.   path_max = (unsigned) PATH_MAX;
  54.   path_max += 2;        /* The getcwd docs say to do this. */
  55.  
  56.   cwd = xmalloc (path_max);
  57.  
  58.   errno = 0;
  59.   while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE)
  60.     {
  61.       path_max += PATH_INCR;
  62.       cwd = xrealloc (cwd, path_max);
  63.       errno = 0;
  64.     }
  65.  
  66.   if (ret == NULL)
  67.     {
  68.       int save_errno = errno;
  69.       free (cwd);
  70.       errno = save_errno;
  71.       return NULL;
  72.     }
  73.   return cwd;
  74. }
  75.