ftello.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* An ftello() function that works around platform bugs.
  2. Copyright (C) 2007, 2009-2013 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. /* Specification. */
  15. #include <stdio.h>
  16. /* Get lseek. */
  17. #include <unistd.h>
  18. #include "stdio-impl.h"
  19. off_t
  20. ftello (FILE *fp)
  21. #undef ftello
  22. #if !HAVE_FTELLO
  23. # undef ftell
  24. # define ftello ftell
  25. #endif
  26. #if _GL_WINDOWS_64_BIT_OFF_T
  27. # undef ftello
  28. # if HAVE__FTELLI64 /* msvc, mingw64 */
  29. # define ftello _ftelli64
  30. # else /* mingw */
  31. # define ftello ftello64
  32. # endif
  33. #endif
  34. {
  35. #if LSEEK_PIPE_BROKEN
  36. /* mingw gives bogus answers rather than failure on non-seekable files. */
  37. if (lseek (fileno (fp), 0, SEEK_CUR) == -1)
  38. return -1;
  39. #endif
  40. #if FTELLO_BROKEN_AFTER_SWITCHING_FROM_READ_TO_WRITE /* Solaris */
  41. /* The Solaris stdio leaves the _IOREAD flag set after reading from a file
  42. reaches EOF and the program then starts writing to the file. ftello
  43. gets confused by this. */
  44. if (fp_->_flag & _IOWRT)
  45. {
  46. off_t pos;
  47. /* Call ftello nevertheless, for the side effects that it does on fp. */
  48. ftello (fp);
  49. /* Compute the file position ourselves. */
  50. pos = lseek (fileno (fp), (off_t) 0, SEEK_CUR);
  51. if (pos >= 0)
  52. {
  53. if ((fp_->_flag & _IONBF) == 0 && fp_->_base != NULL)
  54. pos += fp_->_ptr - fp_->_base;
  55. }
  56. return pos;
  57. }
  58. #endif
  59. #if defined __SL64 && defined __SCLE /* Cygwin */
  60. if ((fp->_flags & __SL64) == 0)
  61. {
  62. /* Cygwin 1.5.0 through 1.5.24 failed to open stdin in 64-bit
  63. mode; but has an ftello that requires 64-bit mode. */
  64. FILE *tmp = fopen ("/dev/null", "r");
  65. if (!tmp)
  66. return -1;
  67. fp->_flags |= __SL64;
  68. fp->_seek64 = tmp->_seek64;
  69. fclose (tmp);
  70. }
  71. #endif
  72. return ftello (fp);
  73. }