xref: /csrg-svn/lib/libc/stdio/fseek.c (revision 15072)
1*15072Skarels /* @(#)fseek.c	4.3 (Berkeley) 09/25/83 */
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;
273163Stoy 			if(!(iop->_flag&_IORW) && c>0&&p<=c
283163Stoy 			    && 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;
363163Stoy 		if (iop->_flag & _IORW) {
373163Stoy 			iop->_ptr = iop->_base;
383163Stoy 			iop->_flag &= ~_IOREAD;
39*15072Skarels 			resync = 0;
403163Stoy 		}
412009Swnj 		p = lseek(fileno(iop), offset-resync, ptrname);
422009Swnj 		iop->_cnt = 0;
432009Swnj 		if (resync)
442009Swnj 			getc(iop);
452009Swnj 	}
463163Stoy 	else if (iop->_flag & (_IOWRT|_IORW)) {
472009Swnj 		fflush(iop);
483163Stoy 		if (iop->_flag & _IORW) {
493163Stoy 			iop->_cnt = 0;
503163Stoy 			iop->_flag &= ~_IOWRT;
513163Stoy 			iop->_ptr = iop->_base;
523163Stoy 		}
532009Swnj 		p = lseek(fileno(iop), offset, ptrname);
542009Swnj 	}
552009Swnj 	return(p==-1?-1:0);
562009Swnj }
57