getdirname.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* vi: set sw=4 ts=4: */
  2. /* Copyright (C) 1992, 1997, 1998, 2000 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <features.h>
  16. #ifdef __USE_GNU
  17. #include <unistd.h>
  18. #include <sys/stat.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. /* Return a malloc'd string containing the current directory name.
  22. If the environment variable `PWD' is set, and its value is correct,
  23. that value is used. */
  24. char *
  25. get_current_dir_name (void)
  26. {
  27. char *pwd;
  28. #ifdef __UCLIBC_HAS_LFS__
  29. struct stat64 dotstat, pwdstat;
  30. #else
  31. struct stat dotstat, pwdstat;
  32. #endif
  33. pwd = getenv ("PWD");
  34. if (pwd != NULL
  35. #ifdef __UCLIBC_HAS_LFS__
  36. && stat64 (".", &dotstat) == 0
  37. && stat64 (pwd, &pwdstat) == 0
  38. #else
  39. && stat (".", &dotstat) == 0
  40. && stat (pwd, &pwdstat) == 0
  41. #endif
  42. && pwdstat.st_dev == dotstat.st_dev
  43. && pwdstat.st_ino == dotstat.st_ino)
  44. /* The PWD value is correct. Use it. */
  45. return strdup (pwd);
  46. return getcwd ((char *) NULL, 0);
  47. }
  48. #endif