getcwd.c revision 77298
133965Sjdp/* Emulate getcwd using getwd.
233965Sjdp   This function is in the public domain. */
333965Sjdp
433965Sjdp/*
533965SjdpNAME
633965Sjdp	getcwd -- get absolute pathname for current working directory
733965Sjdp
833965SjdpSYNOPSIS
933965Sjdp	char *getcwd (char pathname[len], len)
1033965Sjdp
1133965SjdpDESCRIPTION
1233965Sjdp	Copy the absolute pathname for the current working directory into
1333965Sjdp	the supplied buffer and return a pointer to the buffer.  If the
1433965Sjdp	current directory's path doesn't fit in LEN characters, the result
1533965Sjdp	is NULL and errno is set.
1633965Sjdp
1760484Sobrien	If pathname is a null pointer, getcwd() will obtain size bytes of
1860484Sobrien	space using malloc.
1960484Sobrien
2033965SjdpBUGS
2133965Sjdp	Emulated via the getwd() call, which is reasonable for most
2233965Sjdp	systems that do not have getcwd().
2333965Sjdp
2433965Sjdp*/
2533965Sjdp
2660484Sobrien#include "config.h"
2760484Sobrien
2860484Sobrien#ifdef HAVE_SYS_PARAM_H
2933965Sjdp#include <sys/param.h>
3033965Sjdp#endif
3133965Sjdp#include <errno.h>
3277298Sobrien#ifdef HAVE_STRING_H
3377298Sobrien#include <string.h>
3477298Sobrien#endif
3577298Sobrien#ifdef HAVE_STDLIB_H
3677298Sobrien#include <stdlib.h>
3777298Sobrien#endif
3833965Sjdp
3933965Sjdpextern char *getwd ();
4033965Sjdpextern int errno;
4133965Sjdp
4233965Sjdp#ifndef MAXPATHLEN
4333965Sjdp#define MAXPATHLEN 1024
4433965Sjdp#endif
4533965Sjdp
4633965Sjdpchar *
4733965Sjdpgetcwd (buf, len)
4833965Sjdp  char *buf;
4933965Sjdp  int len;
5033965Sjdp{
5133965Sjdp  char ourbuf[MAXPATHLEN];
5233965Sjdp  char *result;
5333965Sjdp
5433965Sjdp  result = getwd (ourbuf);
5533965Sjdp  if (result) {
5633965Sjdp    if (strlen (ourbuf) >= len) {
5733965Sjdp      errno = ERANGE;
5833965Sjdp      return 0;
5933965Sjdp    }
6060484Sobrien    if (!buf) {
6160484Sobrien       buf = (char*)malloc(len);
6260484Sobrien       if (!buf) {
6360484Sobrien           errno = ENOMEM;
6460484Sobrien	   return 0;
6560484Sobrien       }
6660484Sobrien    }
6733965Sjdp    strcpy (buf, ourbuf);
6833965Sjdp  }
6933965Sjdp  return buf;
7033965Sjdp}
71