blob: 5c57291459906db2261c46d3673d6f5a9df1e110 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum79273841991-02-19 12:28:18 +00002/* Two PD getcwd() implementations.
3 Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <guido@cwi.nl>. */
Guido van Rossumde9775a1991-01-21 14:27:52 +00004
Guido van Rossum79273841991-02-19 12:28:18 +00005#include <stdio.h>
6#include <errno.h>
Guido van Rossumde9775a1991-01-21 14:27:52 +00007
Guido van Rossum1d5735e1994-08-30 08:27:36 +00008#ifdef HAVE_GETWD
Guido van Rossum79273841991-02-19 12:28:18 +00009
Guido van Rossum1d5735e1994-08-30 08:27:36 +000010/* Version for BSD systems -- use getwd() */
Guido van Rossum79273841991-02-19 12:28:18 +000011
Guido van Rossum1d5735e1994-08-30 08:27:36 +000012#ifdef HAVE_SYS_PARAM_H
13#include <sys/param.h>
14#endif
15
16#ifndef MAXPATHLEN
17#define MAXPATHLEN 1024
18#endif
Guido van Rossum79273841991-02-19 12:28:18 +000019
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000020extern char *getwd(char *);
Guido van Rossumde9775a1991-01-21 14:27:52 +000021
22char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000023getcwd(char *buf, int size)
Guido van Rossumde9775a1991-01-21 14:27:52 +000024{
25 char localbuf[MAXPATHLEN+1];
26 char *ret;
27
28 if (size <= 0) {
29 errno = EINVAL;
30 return NULL;
31 }
32 ret = getwd(localbuf);
Guido van Rossum582acec2000-06-28 22:07:35 +000033 if (ret != NULL && strlen(localbuf) >= (size_t)size) {
Guido van Rossumde9775a1991-01-21 14:27:52 +000034 errno = ERANGE;
35 return NULL;
36 }
37 if (ret == NULL) {
38 errno = EACCES; /* Most likely error */
39 return NULL;
40 }
41 strncpy(buf, localbuf, size);
42 return buf;
43}
44
Guido van Rossum1d5735e1994-08-30 08:27:36 +000045#else /* !HAVE_GETWD */
Guido van Rossum79273841991-02-19 12:28:18 +000046
Guido van Rossum1d5735e1994-08-30 08:27:36 +000047/* Version for really old UNIX systems -- use pipe from pwd */
Guido van Rossum79273841991-02-19 12:28:18 +000048
Guido van Rossum1d5735e1994-08-30 08:27:36 +000049#ifndef PWD_CMD
Guido van Rossum79273841991-02-19 12:28:18 +000050#define PWD_CMD "/bin/pwd"
Guido van Rossum1d5735e1994-08-30 08:27:36 +000051#endif
Guido van Rossum79273841991-02-19 12:28:18 +000052
53char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000054getcwd(char *buf, int size)
Guido van Rossum79273841991-02-19 12:28:18 +000055{
56 FILE *fp;
57 char *p;
58 int sts;
59 if (size <= 0) {
60 errno = EINVAL;
61 return NULL;
62 }
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;
68 }
69 for (p = buf; *p != '\n'; p++) {
70 if (*p == '\0') {
71 errno = ERANGE;
72 return NULL;
73 }
74 }
75 *p = '\0';
76 return buf;
77}
78
Guido van Rossum1d5735e1994-08-30 08:27:36 +000079#endif /* !HAVE_GETWD */