getdirname.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. struct stat64 dotstat, pwdstat;
  29. pwd = getenv ("PWD");
  30. if (pwd != NULL
  31. && stat64 (".", &dotstat) == 0
  32. && stat64 (pwd, &pwdstat) == 0
  33. && pwdstat.st_dev == dotstat.st_dev
  34. && pwdstat.st_ino == dotstat.st_ino)
  35. /* The PWD value is correct. Use it. */
  36. return strdup (pwd);
  37. return getcwd ((char *) NULL, 0);
  38. }
  39. #endif