date and time created 85/05/30 13:54:43 by mckusick
[unix-history] / usr / src / lib / libc / stdio / filbuf.c
CommitLineData
dbce0e17 1/* @(#)filbuf.c 4.11 (Berkeley) %G% */
4216ca33 2#include <stdio.h>
f4c06a32
KM
3#include <sys/types.h>
4#include <sys/stat.h>
4216ca33
BJ
5char *malloc();
6
7_filbuf(iop)
8register FILE *iop;
9{
f4c06a32
KM
10 int size;
11 struct stat stbuf;
dbce0e17
S
12 static char *smallbuf;
13 static int nfiles;
14 char c;
4216ca33 15
d8af6b8b
MT
16 if (iop->_flag & _IORW)
17 iop->_flag |= _IOREAD;
18
4216ca33
BJ
19 if ((iop->_flag&_IOREAD) == 0)
20 return(EOF);
9acf07ab 21 if (iop->_flag&(_IOSTRG|_IOEOF))
4216ca33
BJ
22 return(EOF);
23tryagain:
24 if (iop->_base==NULL) {
25 if (iop->_flag&_IONBF) {
dbce0e17
S
26 if (nfiles <= 0)
27 nfiles = getdtablesize();
28 if (smallbuf == NULL)
29 smallbuf = malloc(nfiles * sizeof *smallbuf);
30 iop->_base = smallbuf ? &smallbuf[fileno(iop)] : &c;
4216ca33
BJ
31 goto tryagain;
32 }
f4c06a32
KM
33 if (fstat(fileno(iop), &stbuf) < 0 || stbuf.st_blksize <= NULL)
34 size = BUFSIZ;
35 else
36 size = stbuf.st_blksize;
63b1c981
RC
37 if ((iop->_base = malloc(size)) == NULL) {
38 iop->_flag |= _IONBF;
39 goto tryagain;
4216ca33 40 }
63b1c981 41 iop->_flag |= _IOMYBUF;
f4c06a32 42 iop->_bufsiz = size;
4216ca33 43 }
4e0517a3
KM
44 if (iop == stdin) {
45 if (stdout->_flag&_IOLBF)
46 fflush(stdout);
47 if (stderr->_flag&_IOLBF)
48 fflush(stderr);
49 }
f4c06a32
KM
50 iop->_cnt = read(fileno(iop), iop->_base,
51 iop->_flag & _IONBF ? 1 : iop->_bufsiz);
25d7b8e8 52 iop->_ptr = iop->_base;
dbce0e17
S
53 if (iop->_flag & _IONBF && iop->_base == &c)
54 iop->_base = NULL;
4216ca33 55 if (--iop->_cnt < 0) {
d8af6b8b 56 if (iop->_cnt == -1) {
4216ca33 57 iop->_flag |= _IOEOF;
d8af6b8b
MT
58 if (iop->_flag & _IORW)
59 iop->_flag &= ~_IOREAD;
60 } else
4216ca33
BJ
61 iop->_flag |= _IOERR;
62 iop->_cnt = 0;
41e01b3e 63 return(EOF);
4216ca33
BJ
64 }
65 return(*iop->_ptr++&0377);
66}