b2b8f0b6047c7e9bb5a5625baa612eec502ce12c
[platform/upstream/gettext.git] / gnulib-local / lib / xgetcwd.c
1 /* xgetcwd.c -- return current directory with unlimited length
2    Copyright (C) 1992, 1996, 2000, 2003, 2005-2006, 2011 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by David MacKenzie <djm@gnu.ai.mit.edu>.  */
18
19 #include <config.h>
20
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #include "pathmax.h"
28
29 /* In this file, PATH_MAX is the size of an initial memory allocation.  */
30 #ifndef PATH_MAX
31 # define PATH_MAX 8192
32 #endif
33
34 #if HAVE_GETCWD
35 # ifdef VMS
36    /* We want the directory in Unix syntax, not in VMS syntax.  */
37 #  define getcwd(Buf, Max) (getcwd) (Buf, Max, 0)
38 # else
39 char *getcwd ();
40 # endif
41 #else
42 char *getwd ();
43 # define getcwd(Buf, Max) getwd (Buf)
44 #endif
45
46 #include "xalloc.h"
47
48 /* Return the current directory, newly allocated, arbitrarily long.
49    Return NULL and set errno on error. */
50
51 char *
52 xgetcwd ()
53 {
54   char *ret;
55   unsigned path_max;
56   char buf[1024];
57
58   errno = 0;
59   ret = getcwd (buf, sizeof (buf));
60   if (ret != NULL)
61     return xstrdup (buf);
62   if (errno != ERANGE)
63     return NULL;
64
65   path_max = (unsigned) PATH_MAX;
66   path_max += 2;                /* The getcwd docs say to do this. */
67
68   for (;;)
69     {
70       char *cwd = XNMALLOC (path_max, char);
71
72       errno = 0;
73       ret = getcwd (cwd, path_max);
74       if (ret != NULL)
75         return ret;
76       if (errno != ERANGE)
77         {
78           int save_errno = errno;
79           free (cwd);
80           errno = save_errno;
81           return NULL;
82         }
83
84       free (cwd);
85
86       path_max += path_max / 16;
87       path_max += 32;
88     }
89 }