blob: f6cfb34a75fa871202dfa34d9113668cb8d4eee5 [file] [log] [blame]
"Robert P. J. Day"63fc1a92006-07-02 19:47:05 +00001/* vi: set sw=4 ts=4: */
Eric Andersene5dfced2001-04-09 22:48:12 +00002/*
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 *
Glenn L McGrath393183d2003-05-26 14:07:50 +00007 * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersene5dfced2001-04-09 22:48:12 +00008*/
9
10#include <stdlib.h>
11#include <errno.h>
12#include <unistd.h>
13#include <limits.h>
Eric Andersenc0f9d0d2001-08-22 05:35:39 +000014#include <sys/param.h>
Eric Andersene5dfced2001-04-09 22:48:12 +000015#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
25char *
26xgetcwd (char *cwd)
27{
28 char *ret;
29 unsigned path_max;
30
Eric Andersene5dfced2001-04-09 22:48:12 +000031 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
Eric Andersene5dfced2001-04-09 22:48:12 +000037 while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) {
38 path_max += PATH_INCR;
39 cwd = xrealloc (cwd, path_max);
Eric Andersene5dfced2001-04-09 22:48:12 +000040 }
41
42 if (ret == NULL) {
Eric Andersene5dfced2001-04-09 22:48:12 +000043 free (cwd);
Manuel Novoa III cad53642003-03-19 09:13:01 +000044 bb_perror_msg("getcwd()");
Eric Andersene5dfced2001-04-09 22:48:12 +000045 return NULL;
46 }
47
48 return cwd;
49}