117721Speter/* xgetwd.c -- return current directory with unlimited length 232785Speter Copyright (C) 1992, 1997 Free Software Foundation, Inc. 317721Speter 417721Speter This program is free software; you can redistribute it and/or modify 517721Speter it under the terms of the GNU General Public License as published by 617721Speter the Free Software Foundation; either version 2, or (at your option) 717721Speter any later version. 817721Speter 917721Speter This program is distributed in the hope that it will be useful, 1017721Speter but WITHOUT ANY WARRANTY; without even the implied warranty of 1117721Speter MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 1225839Speter GNU General Public License for more details. */ 1317721Speter 1417721Speter/* Derived from xgetcwd.c in e.g. the GNU sh-utils. */ 1517721Speter 1617721Speter#ifdef HAVE_CONFIG_H 1717721Speter#include <config.h> 1817721Speter#endif 1917721Speter 2017721Speter#include "system.h" 2117721Speter 2217721Speter#include <stdio.h> 2317721Speter#include <errno.h> 2417721Speter#ifndef errno 2517721Speterextern int errno; 2617721Speter#endif 2717721Speter#include <sys/types.h> 2817721Speter 2917721Speter/* Amount by which to increase buffer size when allocating more space. */ 3017721Speter#define PATH_INCR 32 3117721Speter 3217721Speterchar *xmalloc (); 3317721Speterchar *xrealloc (); 3417721Speter 3517721Speter/* Return the current directory, newly allocated, arbitrarily long. 3617721Speter Return NULL and set errno on error. */ 3717721Speter 3817721Speterchar * 3917721Speterxgetwd () 4017721Speter{ 4117721Speter char *cwd; 4217721Speter char *ret; 4317721Speter unsigned path_max; 4417721Speter 4517721Speter errno = 0; 4617721Speter path_max = (unsigned) PATH_MAX; 4717721Speter path_max += 2; /* The getcwd docs say to do this. */ 4817721Speter 4917721Speter cwd = xmalloc (path_max); 5017721Speter 5117721Speter errno = 0; 5232785Speter while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) 5317721Speter { 5417721Speter path_max += PATH_INCR; 5517721Speter cwd = xrealloc (cwd, path_max); 5617721Speter errno = 0; 5717721Speter } 5817721Speter 5917721Speter if (ret == NULL) 6017721Speter { 6117721Speter int save_errno = errno; 6217721Speter free (cwd); 6317721Speter errno = save_errno; 6417721Speter return NULL; 6517721Speter } 6617721Speter return cwd; 6717721Speter} 68