getcwd.c 1.53 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
#ifndef MAXPATHLEN
17 18 19
#if defined(PATH_MAX) && PATH_MAX > 1024
#define MAXPATHLEN PATH_MAX
#else
20 21
#define MAXPATHLEN 1024
#endif
22
#endif
23

24
extern char *getwd(char *);
Guido van Rossum's avatar
Guido van Rossum committed
25 26

char *
27
getcwd(char *buf, int size)
Guido van Rossum's avatar
Guido van Rossum committed
28
{
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    char localbuf[MAXPATHLEN+1];
    char *ret;

    if (size <= 0) {
        errno = EINVAL;
        return NULL;
    }
    ret = getwd(localbuf);
    if (ret != NULL && strlen(localbuf) >= (size_t)size) {
        errno = ERANGE;
        return NULL;
    }
    if (ret == NULL) {
        errno = EACCES; /* Most likely error */
        return NULL;
    }
    strncpy(buf, localbuf, size);
    return buf;
Guido van Rossum's avatar
Guido van Rossum committed
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 *
58
getcwd(char *buf, int size)
59
{
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    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;
81 82
}

83
#endif /* !HAVE_GETWD */