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