"Robert P. J. Day" | 63fc1a9 | 2006-07-02 19:47:05 +0000 | [diff] [blame^] | 1 | /* vi: set sw=4 ts=4: */ |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 2 | /* |
| 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 McGrath | 393183d | 2003-05-26 14:07:50 +0000 | [diff] [blame] | 7 | * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru> |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 8 | */ |
| 9 | |
| 10 | #include <stdlib.h> |
| 11 | #include <errno.h> |
| 12 | #include <unistd.h> |
| 13 | #include <limits.h> |
Eric Andersen | c0f9d0d | 2001-08-22 05:35:39 +0000 | [diff] [blame] | 14 | #include <sys/param.h> |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 15 | #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 | |
| 25 | char * |
| 26 | xgetcwd (char *cwd) |
| 27 | { |
| 28 | char *ret; |
| 29 | unsigned path_max; |
| 30 | |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 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 | |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 37 | while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) { |
| 38 | path_max += PATH_INCR; |
| 39 | cwd = xrealloc (cwd, path_max); |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 40 | } |
| 41 | |
| 42 | if (ret == NULL) { |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 43 | free (cwd); |
Manuel Novoa III | cad5364 | 2003-03-19 09:13:01 +0000 | [diff] [blame] | 44 | bb_perror_msg("getcwd()"); |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 45 | return NULL; |
| 46 | } |
| 47 | |
| 48 | return cwd; |
| 49 | } |