branch update for HEAD-2003021201
[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 size_t _read(int _fd, void *_buf, size_t _nbyte)
22 {
23    DWORD _rbyte = 0, nbyte = _nbyte;
24    char *bufp = (char*)_buf;
25    HANDLE hfile;
26    int istext, error;
27
28    DPRINT("_read(fd %d, buf %x, nbyte %d)\n", _fd, _buf, _nbyte);
29
30    /* null read */
31    if(_nbyte == 0)
32       return 0;
33
34    hfile = _get_osfhandle(_fd);
35    istext = __fileno_getmode(_fd) & O_TEXT;
36
37    /* read data */
38    if (!ReadFile(hfile, bufp, nbyte, &_rbyte, NULL))
39    {
40       /* failure */
41       error = GetLastError();
42       if (error == ERROR_BROKEN_PIPE)
43       {
44          return 0;
45       }
46       return -1;
47    }
48       
49    /* text mode */
50    if (_rbyte && istext)
51    {
52       int found_cr = 0;
53       int cr = 0;
54       DWORD count = _rbyte;
55
56       /* repeat for all bytes in the buffer */
57       for(; count; bufp++, count--)
58       {
59 #if 1
60           /* carriage return */
61           if (*bufp == '\r') {
62             found_cr = 1;
63             if (cr != 0) {
64                 *(bufp - cr) = *bufp;
65             }
66             continue;
67           }
68           if (found_cr) {
69             found_cr = 0;
70             if (*bufp == '\n') {
71               cr++;
72               *(bufp - cr) = *bufp;
73             } else {
74             }
75           } else if (cr != 0) {
76             *(bufp - cr) = *bufp;
77           }
78 #else
79          /* carriage return */
80           if (*bufp == '\r') {
81             cr++;
82           }
83          /* shift characters back, to ignore carriage returns */
84           else if (cr != 0) {
85             *(bufp - cr) = *bufp;
86           }
87 #endif
88       }
89       if (found_cr) {
90         cr++;
91       }
92       /* ignore the carriage returns */
93       _rbyte -= cr;
94    }
95    DPRINT("%d\n", _rbyte);
96    return _rbyte;
97 }