blob: 27466816650e2a6e5e571eae070d54689a9ec18e [file] [log] [blame]
Eric Andersene5dfced2001-04-09 22:48:12 +00001/*
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 <vodz@usa.net>
7*/
8
9#include <stdlib.h>
10#include <errno.h>
11#include <unistd.h>
12#include <limits.h>
13#include "libbb.h"
14
15/* Amount to increase buffer size by in each try. */
16#define PATH_INCR 32
17
18/* Return the current directory, newly allocated, arbitrarily long.
19 Return NULL and set errno on error.
20 If argument is not NULL (previous usage allocate memory), call free()
21*/
22
23char *
24xgetcwd (char *cwd)
25{
26 char *ret;
27 unsigned path_max;
28
29 errno = 0;
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 errno = 0;
37 while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) {
38 path_max += PATH_INCR;
39 cwd = xrealloc (cwd, path_max);
40 errno = 0;
41 }
42
43 if (ret == NULL) {
44 int save_errno = errno;
45 free (cwd);
46 errno = save_errno;
47 perror_msg("getcwd()");
48 return NULL;
49 }
50
51 return cwd;
52}