xref: /original-bsd/lib/libc/stdio/filbuf.c (revision 6c57d260)
1 /* @(#)filbuf.c	4.2 (Berkeley) 03/09/81 */
2 #include	<stdio.h>
3 char	*malloc();
4 
5 _filbuf(iop)
6 register FILE *iop;
7 {
8 	static char smallbuf[_NFILE];
9 
10 	if (iop->_flag & _IORW)
11 		iop->_flag |= _IOREAD;
12 
13 	if ((iop->_flag&_IOREAD) == 0)
14 		return(EOF);
15 	if (iop->_flag&_IOSTRG)
16 		return(EOF);
17 tryagain:
18 	if (iop->_base==NULL) {
19 		if (iop->_flag&_IONBF) {
20 			iop->_base = &smallbuf[fileno(iop)];
21 			goto tryagain;
22 		}
23 		if ((iop->_base = malloc(BUFSIZ)) == NULL) {
24 			iop->_flag |= _IONBF;
25 			goto tryagain;
26 		}
27 		iop->_flag |= _IOMYBUF;
28 	}
29 	iop->_ptr = iop->_base;
30 	if (iop == stdin && (stdout->_flag&_IOLBF))
31 		fflush(stdout);
32 	iop->_cnt = read(fileno(iop), iop->_ptr, iop->_flag&_IONBF?1:BUFSIZ);
33 	if (--iop->_cnt < 0) {
34 		if (iop->_cnt == -1) {
35 			iop->_flag |= _IOEOF;
36 			if (iop->_flag & _IORW)
37 				iop->_flag &= ~_IOREAD;
38 		} else
39 			iop->_flag |= _IOERR;
40 		iop->_cnt = 0;
41 		return(-1);
42 	}
43 	return(*iop->_ptr++&0377);
44 }
45