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>
13 int cntcr(char* bufp, int bufsiz);
14 int convert(char* endp, int bufsiz, int n);
15 int _writecnv(int fn, void* buf, size_t bufsiz);
21 int _flsbuf(int c, FILE* f)
28 if (!OPEN4WRITING(f)) {
33 // no file associated with buffer, this is a memory stream
34 if (fileno(f) == -1) {
38 /* if the buffer is not yet allocated, allocate it */
39 if ((base = f->_base) == NULL && (f->_flag & _IONBF) == 0) {
41 if ((f->_base = base = malloc(size)) == NULL) {
43 f->_flag &= ~(_IOFBF|_IOLBF);
46 f->_cnt = f->_bufsiz = size;
49 if (f == stdout && isatty(fileno(stdout))) {
55 if (f->_flag & _IOLBF) {
56 /* in line-buffering mode we get here on each character */
59 if (c == '\n' || rn >= f->_bufsiz) {
60 /* time for real flush */
64 /* we got here because _cnt is wrong, so fix it */
65 /* Negative _cnt causes all output functions to call */
66 /* _flsbuf for each character, thus realizing line-buffering */
70 } else if (f->_flag & _IONBF) {
78 if ((f->_flag & _IOAHEAD) == _IOAHEAD)
79 _lseek(fileno(f), -(rn+f->_cnt), SEEK_CUR);
81 f->_flag &= ~_IOAHEAD;
83 f->_flag &= ~_IODIRTY;
85 n = _write(fileno(f), base, rn);
93 if ((f->_flag & (_IOLBF|_IONBF)) == 0) {
100 wint_t _flswbuf(wchar_t c, FILE* fp)
104 result = _flsbuf((int)c, fp);
107 return (wint_t)result;
110 int _writecnv(int fn, void* buf, size_t siz)
112 char* bufp = (char*)buf;
119 cr1 = cntcr(bufp, bufsiz);
121 memcpy(tmp, bufp + bufsiz - cr1, cr1);
122 cr2 = cntcr(tmp, cr1);
123 convert(bufp, bufsiz - cr2, cr1 - cr2);
124 n = _write(fn, bufp, bufsiz + cr1);
125 convert(tmp, cr1, cr2);
126 n += _write(fn, tmp, cr1 + cr2);
131 int convert(char* endp, int bufsiz, int n)
133 endp = endp + bufsiz + n;
147 int cntcr(char* bufp, int bufsiz)