* find/defs.h: move lstat declarations into defs.h
[findutils.git] / lib / xgetcwd.c
blob28c19caed848f64e11de5914419c07d1fffaadbd
1 /* xgetcwd.c -- return current directory with unlimited length
2 Copyright (C) 1992 Free Software Foundation, Inc.
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.
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.
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. */
18 /* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <errno.h>
26 #ifndef errno
27 extern int errno;
28 #endif
29 #include <sys/types.h>
30 #include "pathmax.h"
32 #ifndef HAVE_GETCWD
33 #define getcwd(buf, max) getwd (buf)
34 #else
35 char *getcwd ();
36 #endif
38 /* Amount to increase buffer size by in each try. */
39 #define PATH_INCR 32
41 char *xmalloc ();
42 char *xrealloc ();
43 void free ();
45 /* Return the current directory, newly allocated, arbitrarily long.
46 Return NULL and set errno on error. */
48 char *
49 xgetcwd ()
51 char *cwd;
52 char *ret;
53 unsigned path_max;
55 errno = 0;
56 path_max = (unsigned) PATH_MAX;
57 path_max += 2; /* The getcwd docs say to do this. */
59 cwd = xmalloc (path_max);
61 errno = 0;
62 while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE)
64 path_max += PATH_INCR;
65 cwd = xrealloc (cwd, path_max);
66 errno = 0;
69 if (ret == NULL)
71 int save_errno = errno;
72 free (cwd);
73 errno = save_errno;
74 return NULL;
76 return cwd;