Pristine Ack-5.5
[Ack-5.5.git] / lang / cem / libcc.ansi / stdio / fillbuf.c
1 /*
2  * fillbuf.c - fill a buffer
3  */
4 /* $Id: fillbuf.c,v 1.7 1994/06/24 11:49:15 ceriel Exp $ */
5
6 #include        <stdio.h>
7 #include        <stdlib.h>
8 #include        "loc_incl.h"
9
10 int _read(int d, char *buf, int nbytes);
11
12 int
13 __fillbuf(register FILE *stream)
14 {
15         static unsigned char ch[FOPEN_MAX];
16         register int i;
17
18         stream->_count = 0;
19         if (fileno(stream) < 0) return EOF;
20         if (io_testflag(stream, (_IOEOF | _IOERR ))) return EOF; 
21         if (!io_testflag(stream, _IOREAD)) {
22                 stream->_flags |= _IOERR;
23                 return EOF;
24         }
25         if (io_testflag(stream, _IOWRITING)) {
26                 stream->_flags |= _IOERR;
27                 return EOF;
28         }
29
30         if (!io_testflag(stream, _IOREADING))
31                 stream->_flags |= _IOREADING;
32         
33         if (!io_testflag(stream, _IONBF) && !stream->_buf) {
34                 stream->_buf = (unsigned char *) malloc(BUFSIZ);
35                 if (!stream->_buf) {
36                         stream->_flags |= _IONBF;
37                 }
38                 else {
39                         stream->_flags |= _IOMYBUF;
40                         stream->_bufsiz = BUFSIZ;
41                 }
42         }
43
44         /* flush line-buffered output when filling an input buffer */
45         for (i = 0; i < FOPEN_MAX; i++) {
46                 if (__iotab[i] && io_testflag(__iotab[i], _IOLBF))
47                         if (io_testflag(__iotab[i], _IOWRITING))
48                                 (void) fflush(__iotab[i]);
49         }
50
51         if (!stream->_buf) {
52                 stream->_buf = &ch[fileno(stream)];
53                 stream->_bufsiz = 1;
54         }
55         stream->_ptr = stream->_buf;
56         stream->_count = _read(stream->_fd, (char *)stream->_buf, stream->_bufsiz);
57
58         if (stream->_count <= 0){
59                 if (stream->_count == 0) {
60                         stream->_flags |= _IOEOF;
61                 }
62                 else 
63                         stream->_flags |= _IOERR;
64
65                 return EOF;
66         }
67         stream->_count--;
68
69         return *stream->_ptr++;
70 }