getdirname.c 1.7 KB

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