:pserver:cvsanon@mok.lvcm.com:/CVS/ReactOS reactos
[reactos.git] / 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/internal/file.h>
13
14 #define NDEBUG
15 #include <msvcrt/msvcrtdbg.h>
16
17 #define BUFSIZE 4096
18
19 size_t _write(int _fd, const void *_buf, size_t _nbyte)
20 {
21    char *tmp, *in, *out;
22    int count, result;
23    DWORD wbyte;
24
25    DPRINT("_write(fd %d, buf %x, nbyte %d)\n", _fd, _buf, _nbyte);
26    if (__fileno_getmode(_fd) & O_TEXT)
27    {
28       result = _nbyte; 
29       tmp = (char*) malloc(BUFSIZE);
30       if (tmp == NULL)
31       {
32          return -1;
33       }
34       count = BUFSIZE;
35       out = tmp;
36       in = (char*) _buf;
37       while (_nbyte--)
38       {
39          if (*in == 0x0a)
40          {
41             *out++ = 0x0d;
42             count--;
43             if (count == 0)
44             {
45                 if (!WriteFile(_get_osfhandle(_fd), tmp, BUFSIZE, &wbyte, NULL))
46                 {
47                    result = -1;
48                    break;
49                 }
50                 if (wbyte < BUFSIZE)
51                 {
52                    result = in - (char*)_buf;
53                    break;
54                 }
55                 count = BUFSIZE;
56                 out = tmp;
57             }
58          }
59          *out++ = *in++;
60          count--;
61          if (count == 0 || _nbyte == 0)
62          {
63             if (!WriteFile(_get_osfhandle(_fd), tmp, BUFSIZE - count, &wbyte, NULL))
64             {
65                 result = -1; 
66                 break;
67             }
68             if (wbyte < BUFSIZE - count)
69             {
70                 result = in - (char*)_buf;
71                 break;
72             }
73             count = BUFSIZE;
74             out = tmp;
75          }
76       }
77       free(tmp);
78       return result;
79    }
80    else
81    {
82       if(!WriteFile(_get_osfhandle(_fd), _buf, _nbyte, &wbyte, NULL))
83       {
84           return -1;
85       }
86       return wbyte;
87    }
88 }