[CRT]
[reactos.git] / reactos / lib / sdk / crt / stdio / _flsbuf.c
1 /*
2 * COPYRIGHT: GNU GPL, see COPYING in the top level directory
3 * PROJECT: ReactOS crt library
4 * FILE: lib/sdk/crt/stdio/_flsbuf.c
5 * PURPOSE: Implementation of _flsbuf / _flswbuf
6 * PROGRAMMER: Timo Kreuzer
7 */
8
9 #include <stdio.h>
10 #include <io.h>
11 #include <tchar.h>
12
13 void __cdecl alloc_buffer(FILE *stream);
14
15 int __cdecl
16 _flsbuf(int ch, FILE *stream)
17 {
18 int count, written;
19
20 /* Check if the stream supports flushing */
21 if ((stream->_flag & _IOSTRG) || !(stream->_flag & (_IORW|_IOWRT)))
22 {
23 stream->_flag |= _IOERR;
24 return EOF;
25 }
26
27 /* Is this was a read buffer */
28 if (stream->_flag & _IOREAD)
29 {
30 /* Must be at the end of the file */
31 if (!(stream->_flag & _IOEOF))
32 {
33 stream->_flag |= _IOERR;
34 stream->_cnt = 0;
35 return EOF;
36 }
37
38 /* Reset buffer */
39 stream->_ptr = stream->_base;
40 }
41
42 /* Fixup flags */
43 stream->_flag &= ~(_IOREAD|_IOEOF);
44 stream->_flag |= _IOWRT;
45
46 /* If we have no buffer, try to allocate one */
47 if (!stream->_base && stream != stdout && stream != stderr)
48 {
49 alloc_buffer(stream);
50 }
51
52 /* Check if we have a buffer now */
53 if (stream->_base)
54 {
55 /* We have one, check if there is something to write */
56 count = stream->_ptr - stream->_base;
57 if (count > 0)
58 written = _write(stream->_file, stream->_base, count);
59 else
60 written = 0;
61
62 /* Reset buffer and put the char into it */
63 stream->_ptr = stream->_base + sizeof(TCHAR);
64 stream->_cnt = stream->_bufsiz - sizeof(TCHAR);
65 *(TCHAR*)stream->_base = ch;
66 }
67 else
68 {
69 /* There is no buffer, write the char directly */
70 count = sizeof(TCHAR);
71 written = _write(stream->_file, &ch, sizeof(TCHAR));
72 }
73
74 /* Check for failure */
75 if (written != count)
76 {
77 stream->_flag |= _IOERR;
78 return EOF;
79 }
80
81 return (TCHAR)ch;
82 }