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