blob: 4f7748123fe9e87165241d5e1ea4103e1af5bc70 [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>
Eric Andersenc0f9d0d2001-08-22 05:35:39 +000013#include <sys/param.h>
Eric Andersene5dfced2001-04-09 22:48:12 +000014#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
24char *
25xgetcwd (char *cwd)
26{
27 char *ret;
28 unsigned path_max;
29
30 errno = 0;
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 errno = 0;
38 while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) {
39 path_max += PATH_INCR;
40 cwd = xrealloc (cwd, path_max);
41 errno = 0;
42 }
43
44 if (ret == NULL) {
45 int save_errno = errno;
46 free (cwd);
47 errno = save_errno;
48 perror_msg("getcwd()");
49 return NULL;
50 }
51
52 return cwd;
53}