make fseek detect and produce an error for invalid whence arguments
[musl.git] / src / stdio / fseek.c
blobc07f7e952642ba3bef35f4eb8a7865e6a8d1b5dc
1 #include "stdio_impl.h"
2 #include <errno.h>
4 int __fseeko_unlocked(FILE *f, off_t off, int whence)
6 /* Fail immediately for invalid whence argument. */
7 if (whence != SEEK_CUR && whence != SEEK_SET && whence != SEEK_END) {
8 errno = EINVAL;
9 return -1;
12 /* Adjust relative offset for unread data in buffer, if any. */
13 if (whence == SEEK_CUR && f->rend) off -= f->rend - f->rpos;
15 /* Flush write buffer, and report error on failure. */
16 if (f->wpos != f->wbase) {
17 f->write(f, 0, 0);
18 if (!f->wpos) return -1;
21 /* Leave writing mode */
22 f->wpos = f->wbase = f->wend = 0;
24 /* Perform the underlying seek. */
25 if (f->seek(f, off, whence) < 0) return -1;
27 /* If seek succeeded, file is seekable and we discard read buffer. */
28 f->rpos = f->rend = 0;
29 f->flags &= ~F_EOF;
31 return 0;
34 int __fseeko(FILE *f, off_t off, int whence)
36 int result;
37 FLOCK(f);
38 result = __fseeko_unlocked(f, off, whence);
39 FUNLOCK(f);
40 return result;
43 int fseek(FILE *f, long off, int whence)
45 return __fseeko(f, off, whence);
48 weak_alias(__fseeko, fseeko);
50 weak_alias(fseeko, fseeko64);