Catch situations where currentframe() returns None. See SF patch #1447410, this is...
[python.git] / Python / getcwd.c
blob5c57291459906db2261c46d3673d6f5a9df1e110
2 /* Two PD getcwd() implementations.
3 Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <guido@cwi.nl>. */
5 #include <stdio.h>
6 #include <errno.h>
8 #ifdef HAVE_GETWD
10 /* Version for BSD systems -- use getwd() */
12 #ifdef HAVE_SYS_PARAM_H
13 #include <sys/param.h>
14 #endif
16 #ifndef MAXPATHLEN
17 #define MAXPATHLEN 1024
18 #endif
20 extern char *getwd(char *);
22 char *
23 getcwd(char *buf, int size)
25 char localbuf[MAXPATHLEN+1];
26 char *ret;
28 if (size <= 0) {
29 errno = EINVAL;
30 return NULL;
32 ret = getwd(localbuf);
33 if (ret != NULL && strlen(localbuf) >= (size_t)size) {
34 errno = ERANGE;
35 return NULL;
37 if (ret == NULL) {
38 errno = EACCES; /* Most likely error */
39 return NULL;
41 strncpy(buf, localbuf, size);
42 return buf;
45 #else /* !HAVE_GETWD */
47 /* Version for really old UNIX systems -- use pipe from pwd */
49 #ifndef PWD_CMD
50 #define PWD_CMD "/bin/pwd"
51 #endif
53 char *
54 getcwd(char *buf, int size)
56 FILE *fp;
57 char *p;
58 int sts;
59 if (size <= 0) {
60 errno = EINVAL;
61 return NULL;
63 if ((fp = popen(PWD_CMD, "r")) == NULL)
64 return NULL;
65 if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) {
66 errno = EACCES; /* Most likely error */
67 return NULL;
69 for (p = buf; *p != '\n'; p++) {
70 if (*p == '\0') {
71 errno = ERANGE;
72 return NULL;
75 *p = '\0';
76 return buf;
79 #endif /* !HAVE_GETWD */