Improved unicode fileio support.
[reactos.git] / reactos / lib / msvcrt / io / write.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS system libraries
4 * FILE: lib/msvcrt/io/write.c
5 * PURPOSE: Writes to a file
6 * PROGRAMER: Boudewijn Dekker
7 * UPDATE HISTORY:
8 * 28/12/98: Created
9 */
10 #include <windows.h>
11 #include <msvcrt/io.h>
12 #include <msvcrt/stdlib.h>
13 #include <msvcrt/internal/file.h>
14
15 #define NDEBUG
16 #include <msvcrt/msvcrtdbg.h>
17
18 #define BUFSIZE 4096
19 /*
20 void ReportLastError(void)
21 {
22 DWORD error = GetLastError();
23 if (error != ERROR_SUCCESS) {
24 PTSTR msg;
25 if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
26 0, error, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (PTSTR)&msg, 0, NULL)) {
27 printf("ReportLastError() %d - %s\n", error, msg);
28 } else {
29 printf("ReportLastError() %d - unknown error\n", error);
30 }
31 LocalFree(msg);
32 }
33 }
34 */
35 size_t _write(int _fd, const void* _buf, size_t _nbyte)
36 {
37 char *tmp, *in, *out;
38 int result;
39 unsigned int count;
40 DWORD wbyte;
41
42 DPRINT("_write(fd %d, buf %x, nbyte %d)\n", _fd, _buf, _nbyte);
43 if (__fileno_getmode(_fd) & O_TEXT) {
44 result = _nbyte;
45 tmp = (char*) malloc(BUFSIZE);
46 if (tmp == NULL) {
47 return -1;
48 }
49 count = BUFSIZE;
50 out = tmp;
51 in = (char*) _buf;
52 while (_nbyte--) {
53 if (*in == 0x0a) {
54 *out++ = 0x0d;
55 count--;
56 if (count == 0) {
57 if (!WriteFile(_get_osfhandle(_fd), tmp, BUFSIZE, &wbyte, NULL)) {
58 //ReportLastError();
59 result = -1;
60 break;
61 }
62 if (wbyte < BUFSIZE) {
63 result = in - (char*)_buf;
64 break;
65 }
66 count = BUFSIZE;
67 out = tmp;
68 }
69 }
70 *out++ = *in++;
71 count--;
72 if (count == 0 || _nbyte == 0) {
73 int tmp_len_debug = strlen(tmp);
74 if (!WriteFile(_get_osfhandle(_fd), tmp, BUFSIZE - count, &wbyte, NULL)) {
75 //ReportLastError();
76 result = -1;
77 tmp_len_debug = 0;
78 break;
79 }
80 if (wbyte < (BUFSIZE - count)) {
81 result = in - (char*)_buf;
82 break;
83 }
84 count = BUFSIZE;
85 out = tmp;
86 }
87 }
88 free(tmp);
89 return result;
90 } else {
91 if(!WriteFile(_get_osfhandle(_fd), _buf, _nbyte, &wbyte, NULL)) {
92 //ReportLastError();
93 return -1;
94 }
95 return wbyte;
96 }
97 }