xref: /csrg-svn/lib/libc/stdio/fseek.c (revision 3163)
1*3163Stoy /* @(#)fseek.c	4.2 (Berkeley) 03/09/81 */
22009Swnj /*
32009Swnj  * Seek for standard library.  Coordinates with buffering.
42009Swnj  */
52009Swnj 
62009Swnj #include	<stdio.h>
72009Swnj 
82009Swnj long lseek();
92009Swnj 
102009Swnj fseek(iop, offset, ptrname)
112009Swnj FILE *iop;
122009Swnj long offset;
132009Swnj {
142009Swnj 	register resync, c;
152009Swnj 	long p;
162009Swnj 
172009Swnj 	iop->_flag &= ~_IOEOF;
182009Swnj 	if (iop->_flag&_IOREAD) {
192009Swnj 		if (ptrname<2 && iop->_base &&
202009Swnj 			!(iop->_flag&_IONBF)) {
212009Swnj 			c = iop->_cnt;
222009Swnj 			p = offset;
232009Swnj 			if (ptrname==0)
242009Swnj 				p += c - lseek(fileno(iop),0L,1);
252009Swnj 			else
262009Swnj 				offset -= c;
27*3163Stoy 			if(!(iop->_flag&_IORW) && c>0&&p<=c
28*3163Stoy 			    && p>=iop->_base-iop->_ptr){
292009Swnj 				iop->_ptr += (int)p;
302009Swnj 				iop->_cnt -= (int)p;
312009Swnj 				return(0);
322009Swnj 			}
332009Swnj 			resync = offset&01;
342009Swnj 		} else
352009Swnj 			resync = 0;
36*3163Stoy 		if (iop->_flag & _IORW) {
37*3163Stoy 			iop->_ptr = iop->_base;
38*3163Stoy 			iop->_flag &= ~_IOREAD;
39*3163Stoy 		}
402009Swnj 		p = lseek(fileno(iop), offset-resync, ptrname);
412009Swnj 		iop->_cnt = 0;
422009Swnj 		if (resync)
432009Swnj 			getc(iop);
442009Swnj 	}
45*3163Stoy 	else if (iop->_flag & (_IOWRT|_IORW)) {
462009Swnj 		fflush(iop);
47*3163Stoy 		if (iop->_flag & _IORW) {
48*3163Stoy 			iop->_cnt = 0;
49*3163Stoy 			iop->_flag &= ~_IOWRT;
50*3163Stoy 			iop->_ptr = iop->_base;
51*3163Stoy 		}
522009Swnj 		p = lseek(fileno(iop), offset, ptrname);
532009Swnj 	}
542009Swnj 	return(p==-1?-1:0);
552009Swnj }
56