xref: /openbsd-src/gnu/lib/libiberty/src/getcwd.c (revision 150b7e42cfa21e6546d96ae514ca23e80d970ac7)
100bf4279Sespie /* Emulate getcwd using getwd.
200bf4279Sespie    This function is in the public domain. */
300bf4279Sespie 
400bf4279Sespie /*
500bf4279Sespie 
637c53322Sespie @deftypefn Supplemental char* getcwd (char *@var{pathname}, int @var{len})
700bf4279Sespie 
800bf4279Sespie Copy the absolute pathname for the current working directory into
937c53322Sespie @var{pathname}, which is assumed to point to a buffer of at least
1037c53322Sespie @var{len} bytes, and return a pointer to the buffer.  If the current
1137c53322Sespie directory's path doesn't fit in @var{len} characters, the result is
1237c53322Sespie @code{NULL} and @code{errno} is set.  If @var{pathname} is a null pointer,
1337c53322Sespie @code{getcwd} will obtain @var{len} bytes of space using
1437c53322Sespie @code{malloc}.
1500bf4279Sespie 
1637c53322Sespie @end deftypefn
1700bf4279Sespie 
1800bf4279Sespie */
1900bf4279Sespie 
2000bf4279Sespie #include "config.h"
2100bf4279Sespie 
2200bf4279Sespie #ifdef HAVE_SYS_PARAM_H
2300bf4279Sespie #include <sys/param.h>
2400bf4279Sespie #endif
2500bf4279Sespie #include <errno.h>
26a22dc43eSespie #ifdef HAVE_STRING_H
27a22dc43eSespie #include <string.h>
28a22dc43eSespie #endif
29a22dc43eSespie #ifdef HAVE_STDLIB_H
30a22dc43eSespie #include <stdlib.h>
31a22dc43eSespie #endif
3200bf4279Sespie 
3300bf4279Sespie extern char *getwd ();
3400bf4279Sespie extern int errno;
3500bf4279Sespie 
3600bf4279Sespie #ifndef MAXPATHLEN
3700bf4279Sespie #define MAXPATHLEN 1024
3800bf4279Sespie #endif
3900bf4279Sespie 
4000bf4279Sespie char *
getcwd(char * buf,size_t len)41*150b7e42Smiod getcwd (char *buf, size_t len)
4200bf4279Sespie {
4300bf4279Sespie   char ourbuf[MAXPATHLEN];
4400bf4279Sespie   char *result;
4500bf4279Sespie 
4600bf4279Sespie   result = getwd (ourbuf);
4700bf4279Sespie   if (result) {
4800bf4279Sespie     if (strlen (ourbuf) >= len) {
4900bf4279Sespie       errno = ERANGE;
5000bf4279Sespie       return 0;
5100bf4279Sespie     }
5200bf4279Sespie     if (!buf) {
5300bf4279Sespie        buf = (char*)malloc(len);
5400bf4279Sespie        if (!buf) {
5500bf4279Sespie            errno = ENOMEM;
5600bf4279Sespie 	   return 0;
5700bf4279Sespie        }
5800bf4279Sespie     }
5900bf4279Sespie     strcpy (buf, ourbuf);
6000bf4279Sespie   }
6100bf4279Sespie   return buf;
6200bf4279Sespie }
63