PageRenderTime 49ms CodeModel.GetById 32ms app.highlight 9ms RepoModel.GetById 4ms app.codeStats 0ms

/Python/getcwd.c

http://unladen-swallow.googlecode.com/
C | 83 lines | 65 code | 14 blank | 4 comment | 18 complexity | 93dd395919f4d13770feb84fd77de7db MD5 | raw file
 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
24extern char *getwd(char *);
25
26char *
27getcwd(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
57char *
58getcwd(char *buf, int size)
59{
60	FILE *fp;
61	char *p;
62	int sts;
63	if (size <= 0) {
64		errno = EINVAL;
65		return NULL;
66	}
67	if ((fp = popen(PWD_CMD, "r")) == NULL)
68		return NULL;
69	if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) {
70		errno = EACCES; /* Most likely error */
71		return NULL;
72	}
73	for (p = buf; *p != '\n'; p++) {
74		if (*p == '\0') {
75			errno = ERANGE;
76			return NULL;
77		}
78	}
79	*p = '\0';
80	return buf;
81}
82
83#endif /* !HAVE_GETWD */