• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* Two PD getcwd() implementations.
3    Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <guido@cwi.nl>. */
4 
5 #include <stdio.h>
6 #include <errno.h>
7 
8 #ifdef HAVE_GETWD
9 
10 /* Version for BSD systems -- use getwd() */
11 
12 #ifdef HAVE_SYS_PARAM_H
13 #include <sys/param.h>
14 #endif
15 
16 #ifndef MAXPATHLEN
17 #if defined(PATH_MAX) && PATH_MAX > 1024
18 #define MAXPATHLEN PATH_MAX
19 #else
20 #define MAXPATHLEN 1024
21 #endif
22 #endif
23 
24 extern char *getwd(char *);
25 
26 char *
getcwd(char * buf,int size)27 getcwd(char *buf, int size)
28 {
29     char localbuf[MAXPATHLEN+1];
30     char *ret;
31 
32     if (size <= 0) {
33         errno = EINVAL;
34         return NULL;
35     }
36     ret = getwd(localbuf);
37     if (ret != NULL && strlen(localbuf) >= (size_t)size) {
38         errno = ERANGE;
39         return NULL;
40     }
41     if (ret == NULL) {
42         errno = EACCES; /* Most likely error */
43         return NULL;
44     }
45     strncpy(buf, localbuf, size);
46     return buf;
47 }
48 
49 #else /* !HAVE_GETWD */
50 
51 /* Version for really old UNIX systems -- use pipe from pwd */
52 
53 #ifndef PWD_CMD
54 #define PWD_CMD "/bin/pwd"
55 #endif
56 
57 char *
getcwd(char * buf,int size)58 getcwd(char *buf, int size)
59 {
60     FILE *fp;
61     char *p;
62     if (size <= 0) {
63         errno = EINVAL;
64         return NULL;
65     }
66     if ((fp = popen(PWD_CMD, "r")) == NULL)
67         return NULL;
68     if (fgets(buf, size, fp) == NULL || pclose(fp) != 0) {
69         errno = EACCES; /* Most likely error */
70         return NULL;
71     }
72     for (p = buf; *p != '\n'; p++) {
73         if (*p == '\0') {
74             errno = ERANGE;
75             return NULL;
76         }
77     }
78     *p = '\0';
79     return buf;
80 }
81 
82 #endif /* !HAVE_GETWD */
83