update for HEAD-2003091401
[reactos.git] / lib / msvcrt / stdio / fflush.c
1 /*
2  * COPYRIGHT:   See COPYING in the top level directory
3  * PROJECT:     ReactOS system libraries
4  * FILE:        lib/msvcrt/stdio/fflush.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 /*
24  * @implemented
25  */
26 int fflush(FILE *f)
27 {
28   char *base;
29   int n, rn;
30
31
32
33   if (f == NULL)
34   {
35      int e = *_errno();
36
37      __set_errno(0);
38     _fwalk((void (*)(FILE *))fflush);
39     if (*_errno())
40       return EOF;
41     __set_errno(e);
42     return 0;
43   }
44
45
46 // nothing to do if stream can not be written to
47
48   if ( !OPEN4WRITING(f) ) {
49         __set_errno (EINVAL);
50         return 0;
51   }
52
53 // discard any unget characters
54
55   f->_flag &= ~_IOUNGETC;
56
57
58 // check for buffered dirty block
59
60   if ( (f->_flag&(_IODIRTY|_IONBF)) ==_IODIRTY && f->_base != NULL)
61   {
62
63     base = f->_base;
64    
65
66 // if the buffer is read ahead and dirty we will flush it entirely
67 // else the buffer is appended to the file to the extend it has valid bytes
68
69     if ( (f->_flag & _IOAHEAD) == _IOAHEAD )
70         rn = n = f->_ptr - base + f->_cnt;
71     else
72         rn = n = f->_ptr - base;
73
74     f->_ptr = base;
75
76     if ((f->_flag & _IOFBF) == _IOFBF) {
77         if ( (f->_flag & _IOAHEAD) == _IOAHEAD )
78             _lseek(fileno(f),-rn, SEEK_CUR);
79     }
80
81     f->_flag &= ~_IOAHEAD;
82
83
84     f->_cnt = (f->_flag&(_IOLBF|_IONBF)) ? 0 : f->_bufsiz;
85
86 // how can write return less than rn without being on error ???
87
88 // possibly commit the flushed data
89 // better open the file in write through mode
90
91     while (rn > 0) {
92       n = _write(fileno(f), base, rn);
93       if (n <= 0) {
94             f->_flag |= _IOERR;
95             return EOF;
96       }
97       rn -= n;
98       base += n;
99     };
100     f->_flag &= ~_IODIRTY;
101
102   }
103   if (OPEN4READING(f) && OPEN4WRITING(f) )
104   {
105     f->_cnt = 0;
106     f->_ptr = f->_base;
107   }
108   return 0;
109 }
110
111 /*
112  * @implemented
113  */
114 int _flushall( void )
115 {
116         return fflush(NULL);
117 }