exp2l: Work around a NetBSD 10.0/i386 bug.
[gnulib.git] / lib / pread.c
blob259678b30dd1c0ed272bbdf48ba33992ceac4c9e
1 /* replacement pread function
2 Copyright (C) 2009-2024 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
9 This file is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 #include <config.h>
19 /* Specification. */
20 #include <unistd.h>
22 #include <errno.h>
24 #define __libc_lseek(f,o,w) lseek (f, o, w)
25 #define __set_errno(Val) errno = (Val)
26 #define __libc_read(f,b,n) read (f, b, n)
28 /* pread substitute for systems that the function, such as mingw32 and BeOS. */
29 /* The following is identical to the function from glibc's
30 sysdeps/posix/pread.c */
32 /* Note: This implementation of pread is not multithread-safe. */
34 ssize_t
35 pread (int fd, void *buf, size_t nbyte, off_t offset)
37 /* Since we must not change the file pointer preserve the value so that
38 we can restore it later. */
39 int saved_errno;
40 ssize_t result;
41 off_t old_offset = __libc_lseek (fd, 0, SEEK_CUR);
42 if (old_offset == (off_t) -1)
43 return -1;
45 /* Set to wanted position. */
46 if (__libc_lseek (fd, offset, SEEK_SET) == (off_t) -1)
47 return -1;
49 /* Write out the data. */
50 result = __libc_read (fd, buf, nbyte);
52 /* Now we have to restore the position. If this fails we have to
53 return this as an error. But if the writing also failed we
54 return this error. */
55 saved_errno = errno;
56 if (__libc_lseek (fd, old_offset, SEEK_SET) == (off_t) -1)
58 if (result == -1)
59 __set_errno (saved_errno);
60 return -1;
62 __set_errno (saved_errno);
64 return result;