1 /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
2 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
4 #include <msvcrt/stdio.h>
5 #include <msvcrt/wchar.h>
6 #include <msvcrt/sys/types.h>
7 #include <msvcrt/stdlib.h>
8 #include <msvcrt/internal/file.h>
10 #include <msvcrt/errno.h>
12 int cntcr(char *bufp, int bufsiz);
13 int convert(char *endp, int bufsiz,int n);
14 int _writecnv(int fn, void *buf, size_t bufsiz);
17 _flsbuf(int c, FILE *f)
26 if (!OPEN4WRITING(f)) {
31 // no file associated with buffer
32 // this is a memory stream
34 if ( fileno(f) == -1 )
37 /* if the buffer is not yet allocated, allocate it */
38 if ((base = f->_base) == NULL && (f->_flag & _IONBF) == 0)
41 if ((f->_base = base = malloc (size)) == NULL)
44 f->_flag &= ~(_IOFBF|_IOLBF);
49 f->_cnt = f->_bufsiz = size;
52 if (f == stdout && isatty (fileno (stdout)))
57 if (f->_flag & _IOLBF)
59 /* in line-buffering mode we get here on each character */
62 if (c == '\n' || rn >= f->_bufsiz)
64 /* time for real flush */
70 /* we got here because _cnt is wrong, so fix it */
71 /* Negative _cnt causes all output functions
72 to call _flsbuf for each character, thus realizing line-buffering */
77 else if (f->_flag & _IONBF)
88 if ( (f->_flag & _IOAHEAD) == _IOAHEAD )
89 _lseek(fileno(f),-(rn+f->_cnt), SEEK_CUR);
91 f->_flag &= ~_IOAHEAD;
96 f->_flag &= ~_IODIRTY;
99 n = _write(fileno(f), base, rn);
110 if ((f->_flag&(_IOLBF|_IONBF)) == 0)
118 wint_t _flswbuf(wchar_t c,FILE *fp)
120 return (wint_t )_flsbuf((int)c,fp);
124 int _writecnv(int fn, void *buf, size_t siz)
126 char *bufp = (char *)buf;
136 cr1 = cntcr(bufp,bufsiz);
139 memcpy(tmp,bufp+bufsiz-cr1,cr1);
140 cr2 = cntcr(tmp,cr1);
142 convert(bufp,bufsiz-cr2,cr1-cr2);
143 n = _write(fn, bufp, bufsiz + cr1);
145 convert(tmp,cr1,cr2);
146 n += _write(fn, tmp, cr1 + cr2);
153 int convert(char *endp, int bufsiz,int n)
155 endp = endp + bufsiz + n;
168 int cntcr(char *bufp, int bufsiz)