2 * flushbuf.c - flush a buffer
4 /* $Id: flushbuf.c,v 1.9 1996/04/24 13:06:00 ceriel Exp $ */
10 #include <sys/types.h>
12 off_t _lseek(int fildes, off_t offset, int whence);
13 int _write(int d, const char *buf, int nbytes);
15 extern void (*_clean)(void);
18 do_write(int d, char *buf, int nbytes)
22 /* POSIX actually allows write() to return a positive value less
23 than nbytes, so loop ...
25 while ((c = _write(d, buf, nbytes)) > 0 && c < nbytes) {
33 __flushbuf(int c, FILE * stream)
36 if (fileno(stream) < 0) return EOF;
37 if (!io_testflag(stream, _IOWRITE)) return EOF;
38 if (io_testflag(stream, _IOREADING) && !feof(stream)) return EOF;
40 stream->_flags &= ~_IOREADING;
41 stream->_flags |= _IOWRITING;
42 if (!io_testflag(stream, _IONBF)) {
44 if (stream == stdout && _isatty(fileno(stdout))) {
46 (unsigned char *) malloc(BUFSIZ))) {
47 stream->_flags |= _IONBF;
49 stream->_flags |= _IOLBF|_IOMYBUF;
50 stream->_bufsiz = BUFSIZ;
55 (unsigned char *) malloc(BUFSIZ))) {
56 stream->_flags |= _IONBF;
58 stream->_flags |= _IOMYBUF;
59 stream->_bufsiz = BUFSIZ;
60 if (!io_testflag(stream, _IOLBF))
61 stream->_count = BUFSIZ - 1;
62 else stream->_count = -1;
65 stream->_ptr = stream->_buf;
69 if (io_testflag(stream, _IONBF)) {
73 if (io_testflag(stream, _IOAPPEND)) {
74 if (_lseek(fileno(stream), 0L, SEEK_END) == -1) {
75 stream->_flags |= _IOERR;
79 if (_write(fileno(stream), &c1, 1) != 1) {
80 stream->_flags |= _IOERR;
83 return (unsigned char) c;
84 } else if (io_testflag(stream, _IOLBF)) {
86 /* stream->_count has been updated in putc macro. */
87 if (c == '\n' || stream->_count == -stream->_bufsiz) {
88 int count = -stream->_count;
90 stream->_ptr = stream->_buf;
93 if (io_testflag(stream, _IOAPPEND)) {
94 if (_lseek(fileno(stream), 0L, SEEK_END) == -1) {
95 stream->_flags |= _IOERR;
99 if (! do_write(fileno(stream), (char *)stream->_buf,
101 stream->_flags |= _IOERR;
106 int count = stream->_ptr - stream->_buf;
108 stream->_count = stream->_bufsiz - 1;
109 stream->_ptr = stream->_buf + 1;
112 if (io_testflag(stream, _IOAPPEND)) {
113 if (_lseek(fileno(stream), 0L, SEEK_END) == -1) {
114 stream->_flags |= _IOERR;
118 if (! do_write(fileno(stream), (char *)stream->_buf, count)) {
120 stream->_flags |= _IOERR;
126 return (unsigned char) c;