lseek.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* An lseek() function that detects pipes.
  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, or (at your option)
  6. 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 along
  12. with this program; if not, see <http://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. /* Specification. */
  15. #include <unistd.h>
  16. #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  17. /* Windows platforms. */
  18. /* Get GetFileType. */
  19. # include <windows.h>
  20. /* Get _get_osfhandle. */
  21. # include "msvc-nothrow.h"
  22. #else
  23. # include <sys/stat.h>
  24. #endif
  25. #include <errno.h>
  26. #undef lseek
  27. off_t
  28. rpl_lseek (int fd, off_t offset, int whence)
  29. {
  30. #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  31. /* mingw lseek mistakenly succeeds on pipes, sockets, and terminals. */
  32. HANDLE h = (HANDLE) _get_osfhandle (fd);
  33. if (h == INVALID_HANDLE_VALUE)
  34. {
  35. errno = EBADF;
  36. return -1;
  37. }
  38. if (GetFileType (h) != FILE_TYPE_DISK)
  39. {
  40. errno = ESPIPE;
  41. return -1;
  42. }
  43. #else
  44. /* BeOS lseek mistakenly succeeds on pipes... */
  45. struct stat statbuf;
  46. if (fstat (fd, &statbuf) < 0)
  47. return -1;
  48. if (!S_ISREG (statbuf.st_mode))
  49. {
  50. errno = ESPIPE;
  51. return -1;
  52. }
  53. #endif
  54. #if _GL_WINDOWS_64_BIT_OFF_T
  55. return _lseeki64 (fd, offset, whence);
  56. #else
  57. return lseek (fd, offset, whence);
  58. #endif
  59. }