Merge from vendor branch OPENSSL:
[dragonfly.git] / contrib / cvs-1.12.9 / lib / xgetwd.c
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 #include "pathmax.h"
22
23 #include <stdio.h>
24 #include <errno.h>
25 #ifndef errno
26 extern int errno;
27 #endif
28 #include <sys/types.h>
29
30 /* Amount by which to increase buffer size when allocating more space. */
31 #define PATH_INCR 32
32
33 char *xmalloc ();
34 char *xrealloc ();
35
36 /* Return the current directory, newly allocated, arbitrarily long.
37    Return NULL and set errno on error. */
38
39 char *
40 xgetwd ()
41 {
42   char *cwd;
43   char *ret;
44   unsigned path_max;
45
46   errno = 0;
47   path_max = (unsigned) PATH_MAX;
48   path_max += 2;                /* The getcwd docs say to do this. */
49
50   cwd = xmalloc (path_max);
51
52   errno = 0;
53   while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE)
54     {
55       path_max += PATH_INCR;
56       cwd = xrealloc (cwd, path_max);
57       errno = 0;
58     }
59
60   if (ret == NULL)
61     {
62       int save_errno = errno;
63       free (cwd);
64       errno = save_errno;
65       return NULL;
66     }
67   return cwd;
68 }