coreutils/lib/xgetcwd.c

86 lines
2.2 KiB
C
Raw Normal View History

1994-04-29 02:39:34 +08:00
/* xgetcwd.c -- return current directory with unlimited length
2003-01-11 06:45:14 +08:00
Copyright (C) 1992, 1996, 2000, 2001, 2003 Free Software Foundation, Inc.
1994-04-29 02:39:34 +08:00
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
1996-07-15 11:36:16 +08:00
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
1994-04-29 02:39:34 +08:00
1996-07-15 11:36:16 +08:00
/* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
1994-04-29 02:39:34 +08:00
1996-11-05 02:11:58 +08:00
#if HAVE_CONFIG_H
1996-07-15 11:56:06 +08:00
# include <config.h>
1994-04-29 02:39:34 +08:00
#endif
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
2003-09-11 17:07:35 +08:00
#include <stdlib.h>
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
1994-04-29 02:39:34 +08:00
1996-11-05 02:11:58 +08:00
#if HAVE_GETCWD
1994-04-29 02:39:34 +08:00
char *getcwd ();
1996-11-05 02:11:58 +08:00
#else
# include "pathmax.h"
# define INITIAL_BUFFER_SIZE (PATH_MAX + 1)
1996-11-05 02:11:58 +08:00
char *getwd ();
# define getcwd(Buf, Max) getwd (Buf)
1994-04-29 02:39:34 +08:00
#endif
#include "xalloc.h"
2003-01-11 06:45:14 +08:00
#include "xgetcwd.h"
2003-03-05 02:07:59 +08:00
/* Return the current directory, newly allocated, assuming it fits
within PATH_MAX bytes -- this is a common system-imposed limit
on how getcwd works.
Upon an out-of-memory error, call xalloc_die.
Upon any other type of error, return NULL. */
1994-04-29 02:39:34 +08:00
char *
2003-01-11 06:45:14 +08:00
xgetcwd (void)
1994-04-29 02:39:34 +08:00
{
#if HAVE_GETCWD_NULL
char *cwd = getcwd (NULL, 0);
if (! cwd && errno == ENOMEM)
xalloc_die ();
return cwd;
#else
/* The initial buffer size for the working directory. A power of 2
detects arithmetic overflow earlier, but is not required. */
# ifndef INITIAL_BUFFER_SIZE
# define INITIAL_BUFFER_SIZE 128
# endif
size_t buf_size = INITIAL_BUFFER_SIZE;
1994-04-29 02:39:34 +08:00
while (1)
1994-04-29 02:39:34 +08:00
{
char *buf = xmalloc (buf_size);
char *cwd = getcwd (buf, buf_size);
int saved_errno;
if (cwd)
return cwd;
saved_errno = errno;
free (buf);
if (saved_errno != ERANGE)
return NULL;
buf_size *= 2;
if (buf_size == 0)
xalloc_die ();
1994-04-29 02:39:34 +08:00
}
#endif
1994-04-29 02:39:34 +08:00
}