getdirname.c 1.9 KB

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