getdirname.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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, write to the Free
  14. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA. */
  16. #include <unistd.h>
  17. #include <sys/stat.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. /* Return a malloc'd string containing the current directory name.
  21. If the environment variable `PWD' is set, and its value is correct,
  22. that value is used. */
  23. char *
  24. get_current_dir_name (void)
  25. {
  26. char *pwd;
  27. #ifdef __USE_LARGEFILE64
  28. struct stat64 dotstat, pwdstat;
  29. #else
  30. struct stat dotstat, pwdstat;
  31. #endif
  32. pwd = getenv ("PWD");
  33. if (pwd != NULL
  34. #ifdef __USE_LARGEFILE64
  35. && stat64 (".", &dotstat) == 0
  36. && stat64 (pwd, &pwdstat) == 0
  37. #else
  38. && stat (".", &dotstat) == 0
  39. && stat (pwd, &pwdstat) == 0
  40. #endif
  41. && pwdstat.st_dev == dotstat.st_dev
  42. && pwdstat.st_ino == dotstat.st_ino)
  43. /* The PWD value is correct. Use it. */
  44. return strdup (pwd);
  45. return getcwd ((char *) NULL, 0);
  46. }