getdirname.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 <features.h>
  17. #include <unistd.h>
  18. #include <sys/stat.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. libc_hidden_proto(strdup)
  22. libc_hidden_proto(getcwd)
  23. libc_hidden_proto(getenv)
  24. #ifdef __UCLIBC_HAS_LFS__
  25. libc_hidden_proto(stat64)
  26. #else
  27. libc_hidden_proto(stat)
  28. #endif
  29. /* Return a malloc'd string containing the current directory name.
  30. If the environment variable `PWD' is set, and its value is correct,
  31. that value is used. */
  32. char *
  33. get_current_dir_name (void)
  34. {
  35. char *pwd;
  36. #ifdef __UCLIBC_HAS_LFS__
  37. struct stat64 dotstat, pwdstat;
  38. #else
  39. struct stat dotstat, pwdstat;
  40. #endif
  41. pwd = getenv ("PWD");
  42. if (pwd != NULL
  43. #ifdef __UCLIBC_HAS_LFS__
  44. && stat64 (".", &dotstat) == 0
  45. && stat64 (pwd, &pwdstat) == 0
  46. #else
  47. && stat (".", &dotstat) == 0
  48. && stat (pwd, &pwdstat) == 0
  49. #endif
  50. && pwdstat.st_dev == dotstat.st_dev
  51. && pwdstat.st_ino == dotstat.st_ino)
  52. /* The PWD value is correct. Use it. */
  53. return strdup (pwd);
  54. return getcwd ((char *) NULL, 0);
  55. }