Use free Windows DDK and compile with latest MinGW releases.
[reactos.git] / reactos / lib / msvcrt / stdio / fwrite.c
1 #include <msvcrti.h>
2
3 #define NDEBUG
4 #include <msvcrtdbg.h>
5
6
7 size_t fwrite(const void *vptr, size_t size, size_t count, FILE *iop)
8 {
9 size_t to_write, n_written;
10 unsigned char *ptr = (unsigned char *)vptr;
11 int copy;
12
13 DPRINT("fwrite(%x, %d, %d, %x)\n", vptr, size, count, iop);
14
15 to_write = size*count;
16 if (!OPEN4WRITING(iop))
17 {
18 __set_errno (EINVAL);
19 return 0;
20 }
21
22 if (iop == NULL)
23 {
24 __set_errno (EINVAL);
25 return 0;
26 }
27
28 if (ferror (iop))
29 return 0;
30 if (vptr == NULL || to_write == 0)
31 return 0;
32
33 if (iop->_base == NULL && !(iop->_flag&_IONBF))
34 {
35 if (EOF == _flsbuf(*ptr++, iop))
36 return 0;
37 if (--to_write == 0)
38 return 1;
39 }
40
41 if (iop->_flag & _IOLBF)
42 {
43 while (to_write > 0)
44 {
45 if (EOF == putc(*ptr++, iop))
46 {
47 iop->_flag |= _IOERR;
48 break;
49 }
50 to_write--;
51 }
52 }
53 else
54 {
55 if (iop->_cnt > 0 && to_write > 0)
56 {
57 copy = min(iop->_cnt, to_write);
58 memcpy(iop->_ptr, ptr, copy);
59 ptr += copy;
60 iop->_ptr += copy;
61 iop->_cnt -= copy;
62 to_write -= copy;
63 iop->_flag |= _IODIRTY;
64 }
65
66 if (to_write > 0)
67 {
68 // if the buffer is dirty it will have to be written now
69 // otherwise the file pointer won't match anymore.
70 fflush(iop);
71 if (to_write >= iop->_bufsiz)
72 {
73 while (to_write > 0)
74 {
75 n_written = _write(_fileno(iop), ptr, to_write);
76 if (n_written <= 0)
77 {
78 iop->_flag |= _IOERR;
79 break;
80 }
81 to_write -= n_written;
82 ptr += n_written;
83 }
84
85 // check to see if this will work with in combination with ungetc
86
87 // the file buffer is empty and there is no read ahead information anymore.
88 iop->_flag &= ~_IOAHEAD;
89 }
90 else
91 {
92 if (EOF != _flsbuf(*ptr++, iop))
93 {
94 if (--to_write > 0)
95 {
96 memcpy(iop->_ptr, ptr, to_write);
97 iop->_ptr += to_write;
98 iop->_cnt -= to_write;
99 iop->_flag |= _IODIRTY;
100 return count;
101 }
102 }
103 }
104 }
105 }
106
107 return count - (to_write/size);
108 }