blob: 1fcdba19815e33c5bc986cc36eea9e1e4ab4c82b [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 *
Glenn L McGrath393183d2003-05-26 14:07:50 +00006 * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersene5dfced2001-04-09 22:48:12 +00007*/
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
Eric Andersene5dfced2001-04-09 22:48:12 +000030 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
Eric Andersene5dfced2001-04-09 22:48:12 +000036 while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) {
37 path_max += PATH_INCR;
38 cwd = xrealloc (cwd, path_max);
Eric Andersene5dfced2001-04-09 22:48:12 +000039 }
40
41 if (ret == NULL) {
Eric Andersene5dfced2001-04-09 22:48:12 +000042 free (cwd);
Manuel Novoa III cad53642003-03-19 09:13:01 +000043 bb_perror_msg("getcwd()");
Eric Andersene5dfced2001-04-09 22:48:12 +000044 return NULL;
45 }
46
47 return cwd;
48}