home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / cvs-1.8.7-src.tgz / tar.out / fsf / cvs / lib / xgetwd.c < prev    next >
C/C++ Source or Header  |  1996-09-28  |  2KB  |  80 lines

  1. /* xgetwd.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. /* Derived from xgetcwd.c in e.g. the GNU sh-utils.  */
  19.  
  20. #ifdef HAVE_CONFIG_H
  21. #include <config.h>
  22. #endif
  23.  
  24. #include "system.h"
  25.  
  26. #include <stdio.h>
  27. #include <errno.h>
  28. #ifndef errno
  29. extern int errno;
  30. #endif
  31. #include <sys/types.h>
  32.  
  33. #ifndef HAVE_GETWD
  34. char *getwd ();
  35. #define GETWD(buf, max) getwd (buf)
  36. #else
  37. char *getcwd ();
  38. #define GETWD(buf, max) getcwd (buf, max)
  39. #endif
  40.  
  41. /* Amount by which to increase buffer size when allocating more space. */
  42. #define PATH_INCR 32
  43.  
  44. char *xmalloc ();
  45. char *xrealloc ();
  46.  
  47. /* Return the current directory, newly allocated, arbitrarily long.
  48.    Return NULL and set errno on error. */
  49.  
  50. char *
  51. xgetwd ()
  52. {
  53.   char *cwd;
  54.   char *ret;
  55.   unsigned path_max;
  56.  
  57.   errno = 0;
  58.   path_max = (unsigned) PATH_MAX;
  59.   path_max += 2;        /* The getcwd docs say to do this. */
  60.  
  61.   cwd = xmalloc (path_max);
  62.  
  63.   errno = 0;
  64.   while ((ret = GETWD (cwd, path_max)) == NULL && errno == ERANGE)
  65.     {
  66.       path_max += PATH_INCR;
  67.       cwd = xrealloc (cwd, path_max);
  68.       errno = 0;
  69.     }
  70.  
  71.   if (ret == NULL)
  72.     {
  73.       int save_errno = errno;
  74.       free (cwd);
  75.       errno = save_errno;
  76.       return NULL;
  77.     }
  78.   return cwd;
  79. }
  80.