1 /* getpwd.c - get the working directory */
5 @deftypefn Supplemental char* getpwd (void)
7 Returns the current working directory. This implementation caches the
8 result on the assumption that the process will not call @code{chdir}
9 between calls to @code{getpwd}.
19 #include <sys/types.h>
32 #ifdef HAVE_SYS_PARAM_H
33 #include <sys/param.h>
42 /* Prototype these in case the system headers don't provide them. */
43 extern char *getpwd ();
44 extern char *getwd ();
46 #include "libiberty.h"
48 /* Virtually every UN*X system now in common use (except for pre-4.3-tahoe
49 BSD systems) now provides getcwd as called for by POSIX. Allow for
50 the few exceptions to the general rule here. */
52 #if !defined(HAVE_GETCWD) && defined(HAVE_GETWD)
53 #define getcwd(buf,len) getwd(buf)
57 #define GUESSPATHLEN (MAXPATHLEN + 1)
59 #define GUESSPATHLEN 100
62 #if !(defined (VMS) || (defined(_WIN32) && !defined(__CYGWIN__)))
64 /* Get the working directory. Use the PWD environment variable if it's
65 set correctly, since this is faster and gives more uniform answers
66 to the user. Yield the working directory if successful; otherwise,
67 yield 0 and set errno. */
73 static int failure_errno
;
77 struct stat dotstat
, pwdstat
;
79 if (!p
&& !(errno
= failure_errno
))
81 if (! ((p
= getenv ("PWD")) != 0
83 && stat (p
, &pwdstat
) == 0
84 && stat (".", &dotstat
) == 0
85 && dotstat
.st_ino
== pwdstat
.st_ino
86 && dotstat
.st_dev
== pwdstat
.st_dev
))
88 /* The shortcut didn't work. Try the slow, ``sure'' way. */
89 for (s
= GUESSPATHLEN
; ! getcwd (p
= xmalloc (s
), s
); s
*= 2)
97 errno
= failure_errno
= e
;
103 /* Cache the result. This assumes that the program does
104 not invoke chdir between calls to getpwd. */
110 #else /* VMS || _WIN32 && !__CYGWIN__ */
113 #define MAXPATHLEN 255
119 static char *pwd
= 0;
122 pwd
= getcwd (xmalloc (MAXPATHLEN
+ 1), MAXPATHLEN
+ 1
130 #endif /* VMS || _WIN32 && !__CYGWIN__ */