update for HEAD-2003091401
[reactos.git] / lib / msvcrt / io / read.c
1 /* $Id$
2  *
3  * COPYRIGHT:   See COPYING in the top level directory
4  * PROJECT:     ReactOS system libraries
5  * FILE:        lib/msvcrt/io/read.c
6  * PURPOSE:     Reads a file
7  * PROGRAMER:   Boudewijn Dekker
8  * UPDATE HISTORY:
9  *              28/12/1998: Created
10  *              03/05/2002: made _read() non-greedy - it now returns as soon as
11  *                          any amount of data has been read. It's the expected
12  *                          behavior for line-buffered streams (KJK::Hyperion)
13  */
14 #include <windows.h>
15 #include <msvcrt/io.h>
16 #include <msvcrt/internal/file.h>
17
18 #define NDEBUG
19 #include <msvcrt/msvcrtdbg.h>
20
21 /*
22  * @implemented
23  */
24 size_t _read(int _fd, void *_buf, size_t _nbyte)
25 {
26    DWORD _rbyte = 0, nbyte = _nbyte;
27    char *bufp = (char*)_buf;
28    HANDLE hfile;
29    int istext, error;
30
31    DPRINT("_read(fd %d, buf %x, nbyte %d)\n", _fd, _buf, _nbyte);
32
33    /* null read */
34    if(_nbyte == 0)
35       return 0;
36
37    hfile = _get_osfhandle(_fd);
38    istext = __fileno_getmode(_fd) & O_TEXT;
39
40    /* read data */
41    if (!ReadFile(hfile, bufp, nbyte, &_rbyte, NULL))
42    {
43       /* failure */
44       error = GetLastError();
45       if (error == ERROR_BROKEN_PIPE)
46       {
47          return 0;
48       }
49       return -1;
50    }
51       
52    /* text mode */
53    if (_rbyte && istext)
54    {
55       int found_cr = 0;
56       int cr = 0;
57       DWORD count = _rbyte;
58
59       /* repeat for all bytes in the buffer */
60       for(; count; bufp++, count--)
61       {
62 #if 1
63           /* carriage return */
64           if (*bufp == '\r') {
65             found_cr = 1;
66             if (cr != 0) {
67                 *(bufp - cr) = *bufp;
68             }
69             continue;
70           }
71           if (found_cr) {
72             found_cr = 0;
73             if (*bufp == '\n') {
74               cr++;
75               *(bufp - cr) = *bufp;
76             } else {
77             }
78           } else if (cr != 0) {
79             *(bufp - cr) = *bufp;
80           }
81 #else
82          /* carriage return */
83           if (*bufp == '\r') {
84             cr++;
85           }
86          /* shift characters back, to ignore carriage returns */
87           else if (cr != 0) {
88             *(bufp - cr) = *bufp;
89           }
90 #endif
91       }
92       if (found_cr) {
93         cr++;
94       }
95       /* ignore the carriage returns */
96       _rbyte -= cr;
97    }
98    DPRINT("%d\n", _rbyte);
99    return _rbyte;
100 }