Pristine Ack-5.5
[Ack-5.5.git] / lang / cem / libcc.ansi / stdio / fflush.c
1 /*
2  * fflush.c - flush stream(s)
3  */
4 /* $Id: fflush.c,v 1.7 1994/06/24 11:48:51 ceriel Exp $ */
5
6 #include        <sys/types.h>
7 #include        <stdio.h>
8 #include        "loc_incl.h"
9
10 int _write(int d, const char *buf, int nbytes);
11 off_t _lseek(int fildes, off_t offset, int whence);
12
13 int
14 fflush(FILE *stream)
15 {
16         int count, c1, i, retval = 0;
17
18         if (!stream) {
19             for(i= 0; i < FOPEN_MAX; i++)
20                 if (__iotab[i] && fflush(__iotab[i]))
21                         retval = EOF;
22             return retval;
23         }
24
25         if (!stream->_buf
26             || (!io_testflag(stream, _IOREADING)
27                 && !io_testflag(stream, _IOWRITING)))
28                 return 0;
29         if (io_testflag(stream, _IOREADING)) {
30                 /* (void) fseek(stream, 0L, SEEK_CUR); */
31                 int adjust = 0;
32                 if (stream->_buf && !io_testflag(stream,_IONBF))
33                         adjust = stream->_count;
34                 stream->_count = 0;
35                 _lseek(fileno(stream), (off_t) adjust, SEEK_CUR);
36                 if (io_testflag(stream, _IOWRITE))
37                         stream->_flags &= ~(_IOREADING | _IOWRITING);
38                 stream->_ptr = stream->_buf;
39                 return 0;
40         } else if (io_testflag(stream, _IONBF)) return 0;
41
42         if (io_testflag(stream, _IOREAD))               /* "a" or "+" mode */
43                 stream->_flags &= ~_IOWRITING;
44
45         count = stream->_ptr - stream->_buf;
46         stream->_ptr = stream->_buf;
47
48         if ( count <= 0 )
49                 return 0;
50
51         if (io_testflag(stream, _IOAPPEND)) {
52                 if (_lseek(fileno(stream), 0L, SEEK_END) == -1) {
53                         stream->_flags |= _IOERR;
54                         return EOF;
55                 }
56         }
57         c1 = _write(stream->_fd, (char *)stream->_buf, count);
58
59         stream->_count = 0;
60
61         if ( count == c1 )
62                 return 0;
63
64         stream->_flags |= _IOERR;
65         return EOF; 
66 }
67
68 void
69 __cleanup(void)
70 {
71         register int i;
72
73         for(i= 0; i < FOPEN_MAX; i++)
74                 if (__iotab[i] && io_testflag(__iotab[i], _IOWRITING))
75                         (void) fflush(__iotab[i]);
76 }