getcwd.c revision 218822
195887Sjmallett/* Emulate getcwd using getwd.
295060Sjmallett   This function is in the public domain. */
31590Srgrimes
41590Srgrimes/*
51590Srgrimes
61590Srgrimes@deftypefn Supplemental char* getcwd (char *@var{pathname}, int @var{len})
71590Srgrimes
81590SrgrimesCopy the absolute pathname for the current working directory into
91590Srgrimes@var{pathname}, which is assumed to point to a buffer of at least
101590Srgrimes@var{len} bytes, and return a pointer to the buffer.  If the current
111590Srgrimesdirectory's path doesn't fit in @var{len} characters, the result is
121590Srgrimes@code{NULL} and @code{errno} is set.  If @var{pathname} is a null pointer,
131590Srgrimes@code{getcwd} will obtain @var{len} bytes of space using
141590Srgrimes@code{malloc}.
151590Srgrimes
161590Srgrimes@end deftypefn
171590Srgrimes
181590Srgrimes*/
191590Srgrimes
201590Srgrimes#include "config.h"
211590Srgrimes
221590Srgrimes#ifdef HAVE_SYS_PARAM_H
231590Srgrimes#include <sys/param.h>
241590Srgrimes#endif
251590Srgrimes#include <errno.h>
261590Srgrimes#ifdef HAVE_STRING_H
271590Srgrimes#include <string.h>
281590Srgrimes#endif
291590Srgrimes#ifdef HAVE_STDLIB_H
301590Srgrimes#include <stdlib.h>
311590Srgrimes#endif
321590Srgrimes
331590Srgrimesextern char *getwd ();
341590Srgrimesextern int errno;
351590Srgrimes
361590Srgrimes#ifndef MAXPATHLEN
371590Srgrimes#define MAXPATHLEN 1024
381590Srgrimes#endif
3995060Sjmallett
4095887Sjmallettchar *
4195887Sjmallettgetcwd (char *buf, size_t len)
4295060Sjmallett{
431590Srgrimes  char ourbuf[MAXPATHLEN];
441590Srgrimes  char *result;
451590Srgrimes
461590Srgrimes  result = getwd (ourbuf);
471590Srgrimes  if (result) {
481590Srgrimes    if (strlen (ourbuf) >= len) {
491590Srgrimes      errno = ERANGE;
501590Srgrimes      return 0;
511590Srgrimes    }
521590Srgrimes    if (!buf) {
5395060Sjmallett       buf = (char*)malloc(len);
541590Srgrimes       if (!buf) {
551590Srgrimes           errno = ENOMEM;
561590Srgrimes	   return 0;
571590Srgrimes       }
581590Srgrimes    }
5995060Sjmallett    strcpy (buf, ourbuf);
6095060Sjmallett  }
6195887Sjmallett  return buf;
6295887Sjmallett}
631590Srgrimes