1/* getpwd.c - get the working directory */ 2 3#include "config.h" 4#include "system.h" 5 6/* Virtually every UN*X system now in common use (except for pre-4.3-tahoe 7 BSD systems) now provides getcwd as called for by POSIX. Allow for 8 the few exceptions to the general rule here. */ 9 10#if !(defined (POSIX) || defined (USG) || defined (VMS)) || defined (HAVE_GETWD) 11#define getcwd(buf,len) getwd(buf) 12#ifdef MAXPATHLEN 13#define GUESSPATHLEN (MAXPATHLEN + 1) 14#else 15#define GUESSPATHLEN 100 16#endif 17#else /* (defined (USG) || defined (VMS)) */ 18/* We actually use this as a starting point, not a limit. */ 19#define GUESSPATHLEN 100 20#endif /* (defined (USG) || defined (VMS)) */ 21 22#if !(defined (VMS) || (defined(_WIN32) && !defined(__CYGWIN__))) 23 24/* Get the working directory. Use the PWD environment variable if it's 25 set correctly, since this is faster and gives more uniform answers 26 to the user. Yield the working directory if successful; otherwise, 27 yield 0 and set errno. */ 28 29char * 30getpwd () 31{ 32 static char *pwd; 33 static int failure_errno; 34 35 char *p = pwd; 36 size_t s; 37 struct stat dotstat, pwdstat; 38 39 if (!p && !(errno = failure_errno)) 40 { 41 if (! ((p = getenv ("PWD")) != 0 42 && *p == '/' 43 && stat (p, &pwdstat) == 0 44 && stat (".", &dotstat) == 0 45 && dotstat.st_ino == pwdstat.st_ino 46 && dotstat.st_dev == pwdstat.st_dev)) 47 48 /* The shortcut didn't work. Try the slow, ``sure'' way. */ 49 for (s = GUESSPATHLEN; ! getcwd (p = xmalloc (s), s); s *= 2) 50 { 51 int e = errno; 52 free (p); 53#ifdef ERANGE 54 if (e != ERANGE) 55#endif 56 { 57 errno = failure_errno = e; 58 p = 0; 59 break; 60 } 61 } 62 63 /* Cache the result. This assumes that the program does 64 not invoke chdir between calls to getpwd. */ 65 pwd = p; 66 } 67 return p; 68} 69 70#else /* VMS || _WIN32 && !__CYGWIN__ */ 71 72#ifndef MAXPATHLEN 73#define MAXPATHLEN 255 74#endif 75 76char * 77getpwd () 78{ 79 static char *pwd = 0; 80 81 if (!pwd) 82 pwd = getcwd (xmalloc (MAXPATHLEN + 1), MAXPATHLEN + 1 83#ifdef VMS 84 , 0 85#endif 86 ); 87 return pwd; 88} 89 90#endif /* VMS || _WIN32 && !__CYGWIN__ */ 91