getcwd.c 1.29 KB
Newer Older
1

2 3
/* Two PD getcwd() implementations.
   Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <guido@cwi.nl>. */
Guido van Rossum's avatar
Guido van Rossum committed
4

5 6
#include <stdio.h>
#include <errno.h>
Guido van Rossum's avatar
Guido van Rossum committed
7

8 9 10
#ifdef HAVE_GETWD

/* Version for BSD systems -- use getwd() */
11

12 13 14
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
15

16 17 18
#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif
19

20
extern char *getwd(char *);
Guido van Rossum's avatar
Guido van Rossum committed
21 22

char *
23
getcwd(char *buf, int size)
Guido van Rossum's avatar
Guido van Rossum committed
24 25 26 27 28 29 30 31 32
{
	char localbuf[MAXPATHLEN+1];
	char *ret;
	
	if (size <= 0) {
		errno = EINVAL;
		return NULL;
	}
	ret = getwd(localbuf);
33
	if (ret != NULL && strlen(localbuf) >= (size_t)size) {
Guido van Rossum's avatar
Guido van Rossum committed
34 35 36 37 38 39 40 41 42 43 44
		errno = ERANGE;
		return NULL;
	}
	if (ret == NULL) {
		errno = EACCES; /* Most likely error */
		return NULL;
	}
	strncpy(buf, localbuf, size);
	return buf;
}

45
#else /* !HAVE_GETWD */
46

47
/* Version for really old UNIX systems -- use pipe from pwd */
48

49
#ifndef PWD_CMD
50
#define PWD_CMD "/bin/pwd"
51
#endif
52 53

char *
54
getcwd(char *buf, int size)
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
{
	FILE *fp;
	char *p;
	int sts;
	if (size <= 0) {
		errno = EINVAL;
		return NULL;
	}
	if ((fp = popen(PWD_CMD, "r")) == NULL)
		return NULL;
	if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) {
		errno = EACCES; /* Most likely error */
		return NULL;
	}
	for (p = buf; *p != '\n'; p++) {
		if (*p == '\0') {
			errno = ERANGE;
			return NULL;
		}
	}
	*p = '\0';
	return buf;
}

79
#endif /* !HAVE_GETWD */