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