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);
18 int _flsbuf(int c, FILE* f)
25 if (!OPEN4WRITING(f)) {
30 // no file associated with buffer, this is a memory stream
31 if (fileno(f) == -1) {
35 /* if the buffer is not yet allocated, allocate it */
36 if ((base = f->_base) == NULL && (f->_flag & _IONBF) == 0) {
38 if ((f->_base = base = malloc(size)) == NULL) {
40 f->_flag &= ~(_IOFBF|_IOLBF);
43 f->_cnt = f->_bufsiz = size;
46 if (f == stdout && isatty(fileno(stdout))) {
52 if (f->_flag & _IOLBF) {
53 /* in line-buffering mode we get here on each character */
56 if (c == '\n' || rn >= f->_bufsiz) {
57 /* time for real flush */
61 /* we got here because _cnt is wrong, so fix it */
62 /* Negative _cnt causes all output functions to call */
63 /* _flsbuf for each character, thus realizing line-buffering */
67 } else if (f->_flag & _IONBF) {
75 if ((f->_flag & _IOAHEAD) == _IOAHEAD)
76 _lseek(fileno(f), -(rn+f->_cnt), SEEK_CUR);
78 f->_flag &= ~_IOAHEAD;
80 f->_flag &= ~_IODIRTY;
82 n = _write(fileno(f), base, rn);
90 if ((f->_flag & (_IOLBF|_IONBF)) == 0) {
97 wint_t _flswbuf(wchar_t c, FILE* fp)
101 result = _flsbuf((int)c, fp);
104 return (wint_t)result;
107 int _writecnv(int fn, void* buf, size_t siz)
109 char* bufp = (char*)buf;
116 cr1 = cntcr(bufp, bufsiz);
118 memcpy(tmp, bufp + bufsiz - cr1, cr1);
119 cr2 = cntcr(tmp, cr1);
120 convert(bufp, bufsiz - cr2, cr1 - cr2);
121 n = _write(fn, bufp, bufsiz + cr1);
122 convert(tmp, cr1, cr2);
123 n += _write(fn, tmp, cr1 + cr2);
128 int convert(char* endp, int bufsiz, int n)
130 endp = endp + bufsiz + n;
144 int cntcr(char* bufp, int bufsiz)