1*16598Skarels /* @(#)filbuf.c 4.9 (Berkeley) 06/21/84 */ 22002Swnj #include <stdio.h> 38326Smckusick #include <sys/types.h> 48326Smckusick #include <sys/stat.h> 52002Swnj char *malloc(); 62002Swnj 72002Swnj _filbuf(iop) 82002Swnj register FILE *iop; 92002Swnj { 108326Smckusick int size; 118326Smckusick struct stat stbuf; 122002Swnj static char smallbuf[_NFILE]; 132002Swnj 143163Stoy if (iop->_flag & _IORW) 153163Stoy iop->_flag |= _IOREAD; 163163Stoy 172002Swnj if ((iop->_flag&_IOREAD) == 0) 182002Swnj return(EOF); 19*16598Skarels if (iop->_flag&(_IOSTRG|_IOEOF)) 202002Swnj return(EOF); 212002Swnj tryagain: 222002Swnj if (iop->_base==NULL) { 232002Swnj if (iop->_flag&_IONBF) { 242002Swnj iop->_base = &smallbuf[fileno(iop)]; 252002Swnj goto tryagain; 262002Swnj } 278326Smckusick if (fstat(fileno(iop), &stbuf) < 0 || stbuf.st_blksize <= NULL) 288326Smckusick size = BUFSIZ; 298326Smckusick else 308326Smckusick size = stbuf.st_blksize; 3116491Sralph if ((iop->_base = malloc(size)) == NULL) { 3216491Sralph iop->_flag |= _IONBF; 3316491Sralph goto tryagain; 342002Swnj } 3516491Sralph iop->_flag |= _IOMYBUF; 368326Smckusick iop->_bufsiz = size; 372002Swnj } 3811306Smckusick if (iop == stdin) { 3911306Smckusick if (stdout->_flag&_IOLBF) 4011306Smckusick fflush(stdout); 4111306Smckusick if (stderr->_flag&_IOLBF) 4211306Smckusick fflush(stderr); 4311306Smckusick } 448326Smckusick iop->_cnt = read(fileno(iop), iop->_base, 458326Smckusick iop->_flag & _IONBF ? 1 : iop->_bufsiz); 463803Ssklower iop->_ptr = iop->_base; 472002Swnj if (--iop->_cnt < 0) { 483163Stoy if (iop->_cnt == -1) { 492002Swnj iop->_flag |= _IOEOF; 503163Stoy if (iop->_flag & _IORW) 513163Stoy iop->_flag &= ~_IOREAD; 523163Stoy } else 532002Swnj iop->_flag |= _IOERR; 542002Swnj iop->_cnt = 0; 552002Swnj return(-1); 562002Swnj } 572002Swnj return(*iop->_ptr++&0377); 582002Swnj } 59