xref: /csrg-svn/lib/libc/stdio/filbuf.c (revision 3803)
1*3803Ssklower /* @(#)filbuf.c	4.3 (Berkeley) 05/19/81 */
22002Swnj #include	<stdio.h>
32002Swnj char	*malloc();
42002Swnj 
52002Swnj _filbuf(iop)
62002Swnj register FILE *iop;
72002Swnj {
82002Swnj 	static char smallbuf[_NFILE];
92002Swnj 
103163Stoy 	if (iop->_flag & _IORW)
113163Stoy 		iop->_flag |= _IOREAD;
123163Stoy 
132002Swnj 	if ((iop->_flag&_IOREAD) == 0)
142002Swnj 		return(EOF);
152002Swnj 	if (iop->_flag&_IOSTRG)
162002Swnj 		return(EOF);
172002Swnj tryagain:
182002Swnj 	if (iop->_base==NULL) {
192002Swnj 		if (iop->_flag&_IONBF) {
202002Swnj 			iop->_base = &smallbuf[fileno(iop)];
212002Swnj 			goto tryagain;
222002Swnj 		}
232002Swnj 		if ((iop->_base = malloc(BUFSIZ)) == NULL) {
242002Swnj 			iop->_flag |= _IONBF;
252002Swnj 			goto tryagain;
262002Swnj 		}
272002Swnj 		iop->_flag |= _IOMYBUF;
282002Swnj 	}
292002Swnj 	if (iop == stdin && (stdout->_flag&_IOLBF))
302002Swnj 		fflush(stdout);
31*3803Ssklower 	iop->_cnt = read(fileno(iop), iop->_base, iop->_flag&_IONBF?1:BUFSIZ);
32*3803Ssklower 	iop->_ptr = iop->_base;
332002Swnj 	if (--iop->_cnt < 0) {
343163Stoy 		if (iop->_cnt == -1) {
352002Swnj 			iop->_flag |= _IOEOF;
363163Stoy 			if (iop->_flag & _IORW)
373163Stoy 				iop->_flag &= ~_IOREAD;
383163Stoy 		} else
392002Swnj 			iop->_flag |= _IOERR;
402002Swnj 		iop->_cnt = 0;
412002Swnj 		return(-1);
422002Swnj 	}
432002Swnj 	return(*iop->_ptr++&0377);
442002Swnj }
45