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