xref: /csrg-svn/lib/libc/stdio/filbuf.c (revision 8326)
1*8326Smckusick /* @(#)filbuf.c	4.4 (Berkeley) 10/05/82 */
22002Swnj #include	<stdio.h>
3*8326Smckusick #include	<sys/types.h>
4*8326Smckusick #include	<sys/stat.h>
52002Swnj char	*malloc();
62002Swnj 
72002Swnj _filbuf(iop)
82002Swnj register FILE *iop;
92002Swnj {
10*8326Smckusick 	int size;
11*8326Smckusick 	struct stat stbuf;
122002Swnj 	static char smallbuf[_NFILE];
13*8326Smckusick 	extern char _sibuf[];
142002Swnj 
153163Stoy 	if (iop->_flag & _IORW)
163163Stoy 		iop->_flag |= _IOREAD;
173163Stoy 
182002Swnj 	if ((iop->_flag&_IOREAD) == 0)
192002Swnj 		return(EOF);
202002Swnj 	if (iop->_flag&_IOSTRG)
212002Swnj 		return(EOF);
222002Swnj tryagain:
232002Swnj 	if (iop->_base==NULL) {
242002Swnj 		if (iop->_flag&_IONBF) {
252002Swnj 			iop->_base = &smallbuf[fileno(iop)];
262002Swnj 			goto tryagain;
272002Swnj 		}
28*8326Smckusick 		if (fstat(fileno(iop), &stbuf) < 0 || stbuf.st_blksize <= NULL)
29*8326Smckusick 			size = BUFSIZ;
30*8326Smckusick 		else
31*8326Smckusick 			size = stbuf.st_blksize;
32*8326Smckusick 		if (iop == stdin)
33*8326Smckusick 			iop->_base = _sibuf;
34*8326Smckusick 		else {
35*8326Smckusick 			if ((iop->_base = malloc(size)) == NULL) {
36*8326Smckusick 				iop->_flag |= _IONBF;
37*8326Smckusick 				goto tryagain;
38*8326Smckusick 			}
39*8326Smckusick 			iop->_flag |= _IOMYBUF;
402002Swnj 		}
41*8326Smckusick 		iop->_bufsiz = size;
422002Swnj 	}
432002Swnj 	if (iop == stdin && (stdout->_flag&_IOLBF))
442002Swnj 		fflush(stdout);
45*8326Smckusick 	iop->_cnt = read(fileno(iop), iop->_base,
46*8326Smckusick 		iop->_flag & _IONBF ? 1 : iop->_bufsiz);
473803Ssklower 	iop->_ptr = iop->_base;
482002Swnj 	if (--iop->_cnt < 0) {
493163Stoy 		if (iop->_cnt == -1) {
502002Swnj 			iop->_flag |= _IOEOF;
513163Stoy 			if (iop->_flag & _IORW)
523163Stoy 				iop->_flag &= ~_IOREAD;
533163Stoy 		} else
542002Swnj 			iop->_flag |= _IOERR;
552002Swnj 		iop->_cnt = 0;
562002Swnj 		return(-1);
572002Swnj 	}
582002Swnj 	return(*iop->_ptr++&0377);
592002Swnj }
60