blob: 0ac450d3bbed94d61d96d8f0698f944940650a4d [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
Eric Andersene5dfced2001-04-09 22:48:12 +000010#include "libbb.h"
11
12/* Amount to increase buffer size by in each try. */
13#define PATH_INCR 32
14
15/* Return the current directory, newly allocated, arbitrarily long.
16 Return NULL and set errno on error.
17 If argument is not NULL (previous usage allocate memory), call free()
18*/
19
20char *
Denis Vlasenkoc2905632006-09-23 16:01:09 +000021xgetcwd(char *cwd)
Eric Andersene5dfced2001-04-09 22:48:12 +000022{
Denis Vlasenkoc2905632006-09-23 16:01:09 +000023 char *ret;
24 unsigned path_max;
Eric Andersene5dfced2001-04-09 22:48:12 +000025
Denis Vlasenkoc2905632006-09-23 16:01:09 +000026 path_max = (unsigned) PATH_MAX;
27 path_max += 2; /* The getcwd docs say to do this. */
Eric Andersene5dfced2001-04-09 22:48:12 +000028
Denis Vlasenkoc2905632006-09-23 16:01:09 +000029 if (cwd==0)
30 cwd = xmalloc(path_max);
Eric Andersene5dfced2001-04-09 22:48:12 +000031
Denis Vlasenkoc2905632006-09-23 16:01:09 +000032 while ((ret = getcwd(cwd, path_max)) == NULL && errno == ERANGE) {
33 path_max += PATH_INCR;
34 cwd = xrealloc(cwd, path_max);
35 }
Eric Andersene5dfced2001-04-09 22:48:12 +000036
Denis Vlasenkoc2905632006-09-23 16:01:09 +000037 if (ret == NULL) {
38 free(cwd);
39 bb_perror_msg("getcwd");
40 return NULL;
41 }
Eric Andersene5dfced2001-04-09 22:48:12 +000042
Denis Vlasenkoc2905632006-09-23 16:01:09 +000043 return cwd;
Eric Andersene5dfced2001-04-09 22:48:12 +000044}