Back to index

cell-binutils  2.17cvs20070401
getcwd.c
Go to the documentation of this file.
00001 /* Emulate getcwd using getwd.
00002    This function is in the public domain. */
00003 
00004 /*
00005 
00006 @deftypefn Supplemental char* getcwd (char *@var{pathname}, int @var{len})
00007 
00008 Copy the absolute pathname for the current working directory into
00009 @var{pathname}, which is assumed to point to a buffer of at least
00010 @var{len} bytes, and return a pointer to the buffer.  If the current
00011 directory's path doesn't fit in @var{len} characters, the result is
00012 @code{NULL} and @code{errno} is set.  If @var{pathname} is a null pointer,
00013 @code{getcwd} will obtain @var{len} bytes of space using
00014 @code{malloc}.
00015 
00016 @end deftypefn
00017 
00018 */
00019 
00020 #include "config.h"
00021 
00022 #ifdef HAVE_SYS_PARAM_H
00023 #include <sys/param.h>
00024 #endif
00025 #include <errno.h>
00026 #ifdef HAVE_STRING_H
00027 #include <string.h>
00028 #endif
00029 #ifdef HAVE_STDLIB_H
00030 #include <stdlib.h>
00031 #endif
00032 
00033 extern char *getwd ();
00034 extern int errno;
00035 
00036 #ifndef MAXPATHLEN
00037 #define MAXPATHLEN 1024
00038 #endif
00039 
00040 char *
00041 getcwd (char *buf, size_t len)
00042 {
00043   char ourbuf[MAXPATHLEN];
00044   char *result;
00045 
00046   result = getwd (ourbuf);
00047   if (result) {
00048     if (strlen (ourbuf) >= len) {
00049       errno = ERANGE;
00050       return 0;
00051     }
00052     if (!buf) {
00053        buf = (char*)malloc(len);
00054        if (!buf) {
00055            errno = ENOMEM;
00056           return 0;
00057        }
00058     }
00059     strcpy (buf, ourbuf);
00060   }
00061   return buf;
00062 }