7848bb3086d65f9ce28241f5fd01d383a41127ca
[reactos.git] / reactos / lib / msvcrt / stdio / fflush.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS system libraries
4 * FILE: lib/crtdll/conio/kbhit.c
5 * PURPOSE: Checks for keyboard hits
6 * PROGRAMER: Boudewijn Dekker
7 * UPDATE HISTORY:
8 * 28/12/98: Created
9 */
10 /* Copyright (C) 1998 DJ Delorie, see COPYING.DJ for details */
11 /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
12 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
13
14 #include <msvcrt/stdio.h>
15 #include <msvcrt/errno.h>
16 #include <msvcrt/sys/types.h>
17 #include <msvcrt/sys/stat.h>
18 #include <msvcrt/stdlib.h>
19 #include <msvcrt/internal/file.h>
20 #include <msvcrt/io.h>
21
22
23 int fflush(FILE *f)
24 {
25 char *base;
26 int n, rn;
27
28
29
30 if (f == NULL)
31 {
32 int e = errno;
33
34 __set_errno(0);
35 _fwalk((void (*)(FILE *))fflush);
36 if (_errno)
37 return EOF;
38 __set_errno(e);
39 return 0;
40 }
41
42
43 // nothing to do if stream can not be written to
44
45 if ( !OPEN4WRITING(f) ) {
46 __set_errno (EINVAL);
47 return 0;
48 }
49
50 // discard any unget characters
51
52 f->_flag &= ~_IOUNGETC;
53
54
55 // check for buffered dirty block
56
57 if ( (f->_flag&(_IODIRTY|_IONBF)) ==_IODIRTY && f->_base != NULL)
58 {
59
60 base = f->_base;
61
62
63 // if the buffer is read ahead and dirty we will flush it entirely
64 // else the buffer is appended to the file to the extend it has valid bytes
65
66 if ( (f->_flag & _IOAHEAD) == _IOAHEAD )
67 rn = n = f->_ptr - base + f->_cnt;
68 else
69 rn = n = f->_ptr - base;
70
71 f->_ptr = base;
72
73 if ((f->_flag & _IOFBF) == _IOFBF) {
74 if ( (f->_flag & _IOAHEAD) == _IOAHEAD )
75 _lseek(fileno(f),-rn, SEEK_CUR);
76 }
77
78 f->_flag &= ~_IOAHEAD;
79
80
81 f->_cnt = (f->_flag&(_IOLBF|_IONBF)) ? 0 : f->_bufsiz;
82
83 // how can write return less than rn without being on error ???
84
85 // possibly commit the flushed data
86 // better open the file in write through mode
87
88 while (rn > 0) {
89 n = _write(fileno(f), base, rn);
90 if (n <= 0) {
91 f->_flag |= _IOERR;
92 return EOF;
93 }
94 rn -= n;
95 base += n;
96 };
97 f->_flag &= ~_IODIRTY;
98
99 }
100 if (OPEN4READING(f) && OPEN4WRITING(f) )
101 {
102 f->_cnt = 0;
103 f->_ptr = f->_base;
104 }
105 return 0;
106 }
107
108 int _flushall( void )
109 {
110 return fflush(NULL);
111 }