pwrite.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Write block to given position in file without changing file pointer.
  2. POSIX version.
  3. Copyright (C) 1997-1999, 2002, 2011-2014 Free Software Foundation, Inc.
  4. This file is part of the GNU C Library.
  5. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
  6. This program is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 3 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  16. #include <config.h>
  17. /* Specification. */
  18. #include <unistd.h>
  19. #include <errno.h>
  20. #define __libc_lseek(f,o,w) lseek (f, o, w)
  21. #define __set_errno(Val) errno = (Val)
  22. #define __libc_write(f,b,n) write (f, b, n)
  23. /* Note: This implementation of pwrite is not multithread-safe. */
  24. ssize_t
  25. pwrite (int fd, const 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_write (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. }