pread.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* replacement pread function
  2. Copyright (C) 2009-2014 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 <unistd.h>
  16. #include <errno.h>
  17. #define __libc_lseek(f,o,w) lseek (f, o, w)
  18. #define __set_errno(Val) errno = (Val)
  19. #define __libc_read(f,b,n) read (f, b, n)
  20. /* pread substitute for systems that the function, such as mingw32 and BeOS. */
  21. /* The following is identical to the function from glibc's
  22. sysdeps/posix/pread.c */
  23. /* Note: This implementation of pread is not multithread-safe. */
  24. ssize_t
  25. pread (int fd, void *buf, size_t nbyte, off_t offset)
  26. {
  27. /* Since we must not change the file pointer preserve the value so that
  28. we can restore it later. */
  29. int save_errno;
  30. ssize_t result;
  31. off_t old_offset = __libc_lseek (fd, 0, SEEK_CUR);
  32. if (old_offset == (off_t) -1)
  33. return -1;
  34. /* Set to wanted position. */
  35. if (__libc_lseek (fd, offset, SEEK_SET) == (off_t) -1)
  36. return -1;
  37. /* Write out the data. */
  38. result = __libc_read (fd, buf, nbyte);
  39. /* Now we have to restore the position. If this fails we have to
  40. return this as an error. But if the writing also failed we
  41. return this error. */
  42. save_errno = errno;
  43. if (__libc_lseek (fd, old_offset, SEEK_SET) == (off_t) -1)
  44. {
  45. if (result == -1)
  46. __set_errno (save_errno);
  47. return -1;
  48. }
  49. __set_errno (save_errno);
  50. return result;
  51. }