xref: /minix3/lib/libc/stdio/fseek.c (revision 58a2b0008e28f606a7f7f5faaeaba4faac57a1ea)
1 /*
2  * fseek.c - perform an fseek
3  */
4 /* $Header$ */
5 
6 #include	<assert.h>
7 #include	<stdio.h>
8 
9 #if	(SEEK_CUR != 1) || (SEEK_END != 2) || (SEEK_SET != 0)
10 #error SEEK_* values are wrong
11 #endif
12 
13 #include	"loc_incl.h"
14 
15 #include	<sys/types.h>
16 
17 off_t _lseek(int fildes, off_t offset, int whence);
18 
19 int
20 fseek(FILE *stream, long int offset, int whence)
21 {
22 	assert(sizeof(offset) == sizeof(off_t));
23 	return fseeko(stream, (off_t) offset, whence);
24 }
25 
26 int
27 fseeko(FILE *stream, off_t offset, int whence)
28 {
29 	int adjust = 0;
30 	long pos;
31 
32 	stream->_flags &= ~(_IOEOF | _IOERR);
33 	/* Clear both the end of file and error flags */
34 
35 	if (io_testflag(stream, _IOREADING)) {
36 		if (whence == SEEK_CUR
37 		    && stream->_buf
38 		    && !io_testflag(stream,_IONBF))
39 			adjust = stream->_count;
40 		stream->_count = 0;
41 	} else if (io_testflag(stream,_IOWRITING)) {
42 		fflush(stream);
43 	} else	/* neither reading nor writing. The buffer must be empty */
44 		/* EMPTY */ ;
45 
46 	pos = _lseek(fileno(stream), offset - adjust, whence);
47 	if (io_testflag(stream, _IOREAD) && io_testflag(stream, _IOWRITE))
48 		stream->_flags &= ~(_IOREADING | _IOWRITING);
49 
50 	stream->_ptr = stream->_buf;
51 	return ((pos == -1) ? -1 : 0);
52 }
53