More removal of "#if 0" content.
[oweals/busybox.git] / libbb / xgetcwd.c
1 /*
2  * xgetcwd.c -- return current directory with unlimited length
3  * Copyright (C) 1992, 1996 Free Software Foundation, Inc.
4  * Written by David MacKenzie <djm@gnu.ai.mit.edu>.
5  *
6  * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru>
7 */
8
9 #include <stdlib.h>
10 #include <errno.h>
11 #include <unistd.h>
12 #include <limits.h>
13 #include <sys/param.h>
14 #include "libbb.h"
15
16 /* Amount to increase buffer size by in each try. */
17 #define PATH_INCR 32
18
19 /* Return the current directory, newly allocated, arbitrarily long.
20    Return NULL and set errno on error.
21    If argument is not NULL (previous usage allocate memory), call free()
22 */
23
24 char *
25 xgetcwd (char *cwd)
26 {
27   char *ret;
28   unsigned path_max;
29
30   path_max = (unsigned) PATH_MAX;
31   path_max += 2;                /* The getcwd docs say to do this. */
32
33   if(cwd==0)
34         cwd = xmalloc (path_max);
35
36   while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) {
37       path_max += PATH_INCR;
38       cwd = xrealloc (cwd, path_max);
39   }
40
41   if (ret == NULL) {
42       free (cwd);
43       bb_perror_msg("getcwd()");
44       return NULL;
45   }
46
47   return cwd;
48 }