document sticky EOF
[unix-history] / usr / src / lib / libc / stdio / filbuf.c
CommitLineData
586c39b1
DF
1/*
2 * Copyright (c) 1980 Regents of the University of California.
3 * All rights reserved. The Berkeley software License Agreement
4 * specifies the terms and conditions for redistribution.
5 */
6
2ce81398
DS
7#if defined(LIBC_SCCS) && !defined(lint)
8static char sccsid[] = "@(#)filbuf.c 5.3 (Berkeley) %G%";
9#endif LIBC_SCCS and not lint
586c39b1 10
4216ca33 11#include <stdio.h>
f4c06a32
KM
12#include <sys/types.h>
13#include <sys/stat.h>
4216ca33
BJ
14char *malloc();
15
16_filbuf(iop)
17register FILE *iop;
18{
f4c06a32
KM
19 int size;
20 struct stat stbuf;
7baa89ad 21 extern char *_smallbuf;
dbce0e17 22 char c;
4216ca33 23
d8af6b8b
MT
24 if (iop->_flag & _IORW)
25 iop->_flag |= _IOREAD;
26
4216ca33
BJ
27 if ((iop->_flag&_IOREAD) == 0)
28 return(EOF);
9acf07ab 29 if (iop->_flag&(_IOSTRG|_IOEOF))
4216ca33
BJ
30 return(EOF);
31tryagain:
32 if (iop->_base==NULL) {
33 if (iop->_flag&_IONBF) {
7baa89ad 34 iop->_base = _smallbuf ? &_smallbuf[fileno(iop)] : &c;
4216ca33
BJ
35 goto tryagain;
36 }
f4c06a32
KM
37 if (fstat(fileno(iop), &stbuf) < 0 || stbuf.st_blksize <= NULL)
38 size = BUFSIZ;
39 else
40 size = stbuf.st_blksize;
63b1c981
RC
41 if ((iop->_base = malloc(size)) == NULL) {
42 iop->_flag |= _IONBF;
43 goto tryagain;
4216ca33 44 }
63b1c981 45 iop->_flag |= _IOMYBUF;
f4c06a32 46 iop->_bufsiz = size;
4216ca33 47 }
4e0517a3
KM
48 if (iop == stdin) {
49 if (stdout->_flag&_IOLBF)
50 fflush(stdout);
51 if (stderr->_flag&_IOLBF)
52 fflush(stderr);
53 }
f4c06a32
KM
54 iop->_cnt = read(fileno(iop), iop->_base,
55 iop->_flag & _IONBF ? 1 : iop->_bufsiz);
25d7b8e8 56 iop->_ptr = iop->_base;
dbce0e17
S
57 if (iop->_flag & _IONBF && iop->_base == &c)
58 iop->_base = NULL;
4216ca33 59 if (--iop->_cnt < 0) {
d8af6b8b 60 if (iop->_cnt == -1) {
4216ca33 61 iop->_flag |= _IOEOF;
d8af6b8b
MT
62 if (iop->_flag & _IORW)
63 iop->_flag &= ~_IOREAD;
64 } else
4216ca33
BJ
65 iop->_flag |= _IOERR;
66 iop->_cnt = 0;
41e01b3e 67 return(EOF);
4216ca33
BJ
68 }
69 return(*iop->_ptr++&0377);
70}