chiark / gitweb /
fix readable logic
[innduct.git] / lib / pwrite.c
1 /*  $Id: pwrite.c 5049 2001-12-12 09:06:00Z rra $
2 **
3 **  Replacement for a missing pwrite.
4 **
5 **  Written by Russ Allbery <rra@stanford.edu>
6 **  This work is hereby placed in the public domain by its author.
7 **
8 **  Provides the same functionality as the standard library routine pwrite
9 **  for those platforms that don't have it.  Note that pwrite requires that
10 **  the file pointer not move and without the library function, we can't
11 **  copy that behavior; instead, we approximate it by moving the file
12 **  pointer and then moving it back.  This may break threaded programs.
13 */
14
15 #include "config.h"
16 #include "clibrary.h"
17 #include <errno.h>
18
19 /* If we're running the test suite, rename pread to avoid conflicts with the
20    system version.  #undef first because large file support may define a
21    macro pwrite (pointing to pwrite64) on some platforms (e.g. Solaris). */
22 #if TESTING
23 # undef pwrite
24 # define pwrite test_pwrite
25 ssize_t test_pwrite(int, const void *, size_t, off_t);
26 #endif
27
28 ssize_t
29 pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
30 {
31     off_t current;
32     ssize_t nwritten;
33     int oerrno;
34
35     current = lseek(fd, 0, SEEK_CUR);
36     if (current == (off_t) -1 || lseek(fd, offset, SEEK_SET) == (off_t) -1)
37         return -1;
38
39     nwritten = write(fd, buf, nbyte);
40
41     /* Ignore errors in restoring the file position; this isn't ideal, but
42        reporting a failed write when the write succeeded is worse.  Make
43        sure that errno, if set, is set by write and not lseek. */
44     oerrno = errno;
45     lseek(fd, current, SEEK_SET);
46     errno = oerrno;
47     return nwritten;
48 }