getcwd.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* Emulate getcwd using getwd.
  2. This function is in the public domain. */
  3. /*
  4. @deftypefn Supplemental char* getcwd (char *@var{pathname}, int @var{len})
  5. Copy the absolute pathname for the current working directory into
  6. @var{pathname}, which is assumed to point to a buffer of at least
  7. @var{len} bytes, and return a pointer to the buffer. If the current
  8. directory's path doesn't fit in @var{len} characters, the result is
  9. @code{NULL} and @code{errno} is set. If @var{pathname} is a null pointer,
  10. @code{getcwd} will obtain @var{len} bytes of space using
  11. @code{malloc}.
  12. @end deftypefn
  13. */
  14. #include "config.h"
  15. #ifdef HAVE_SYS_PARAM_H
  16. #include <sys/param.h>
  17. #endif
  18. #include <errno.h>
  19. #ifdef HAVE_STRING_H
  20. #include <string.h>
  21. #endif
  22. #ifdef HAVE_STDLIB_H
  23. #include <stdlib.h>
  24. #endif
  25. extern char *getwd ();
  26. extern int errno;
  27. #ifndef MAXPATHLEN
  28. #define MAXPATHLEN 1024
  29. #endif
  30. char *
  31. getcwd (char *buf, size_t len)
  32. {
  33. char ourbuf[MAXPATHLEN];
  34. char *result;
  35. result = getwd (ourbuf);
  36. if (result) {
  37. if (strlen (ourbuf) >= len) {
  38. errno = ERANGE;
  39. return 0;
  40. }
  41. if (!buf) {
  42. buf = (char*)malloc(len);
  43. if (!buf) {
  44. errno = ENOMEM;
  45. return 0;
  46. }
  47. }
  48. strcpy (buf, ourbuf);
  49. }
  50. return buf;
  51. }