branch update for HEAD-2003021201
[reactos.git] / lib / msvcrt / stdio / filbuf.c
1 /* Copyright (C) 1997 DJ Delorie, see COPYING.DJ for details */
2 /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
3 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
4
5 #include <msvcrt/stdio.h>
6 #include <msvcrt/sys/types.h>
7 #include <msvcrt/stdlib.h>
8 #include <msvcrt/string.h>
9 #include <msvcrt/internal/file.h>
10 #include <msvcrt/io.h>
11 #include <msvcrt/wchar.h>
12 #include <msvcrt/errno.h>
13
14 int _readcnv(int fn, void* buf, size_t siz);
15
16 int _filbuf(FILE* f)
17 {
18   int size;
19   char c;
20  
21   if ( !OPEN4READING(f)) {
22         __set_errno (EINVAL);
23         return EOF;
24   }
25   if (f->_flag&(_IOSTRG|_IOEOF))
26     return EOF;
27   f->_flag &= ~_IOUNGETC;
28
29   if (f->_base == NULL && (f->_flag & _IONBF) == 0) {
30     size = 4096;
31     if ((f->_base = malloc(size+1)) == NULL) {
32         // error ENOMEM
33       f->_flag |= _IONBF;
34       f->_flag &= ~(_IOFBF|_IOLBF);
35     } else {
36       f->_flag |= _IOMYBUF;
37       f->_bufsiz = size;
38     }
39   }
40   if (f->_flag&_IONBF)
41     f->_base = &c;
42
43   // flush stdout before reading from stdin 
44   if (f == stdin) {
45     if (stdout->_flag&_IOLBF)
46       fflush(stdout);
47     if (stderr->_flag&_IOLBF)
48       fflush(stderr);
49   }
50
51   // if we have a dirty stream we flush it
52   if ((f->_flag &_IODIRTY) == _IODIRTY)
53          fflush(f);
54
55
56
57   f->_cnt = _read(fileno(f), f->_base, f->_flag & _IONBF ? 1 : f->_bufsiz  );
58   f->_flag |= _IOAHEAD;
59
60   if(__is_text_file(f) && f->_cnt>0)
61   {
62     /* truncate text file at Ctrl-Z */
63     char *cz=memchr(f->_base, 0x1A, f->_cnt);
64     if(cz)
65     {
66       int newcnt = cz - f->_base;
67       lseek(fileno(f), -(f->_cnt - newcnt), SEEK_CUR);
68       f->_cnt = newcnt;
69     }
70   }
71
72   f->_ptr = f->_base;
73
74   if (f->_flag & _IONBF) 
75      f->_base = NULL; // statically allocated buffer for sprintf
76   
77
78 //check for error
79   if (f->_cnt <= 0) {
80     if (f->_cnt == 0) {
81       f->_flag |= _IOEOF;
82     } else
83       f->_flag |= _IOERR;
84     f->_cnt = 0;
85
86 // should set errno 
87
88     return EOF;
89   }
90
91   f->_cnt--;
92
93   return *f->_ptr++ & 0377;
94 }
95
96 wint_t  _filwbuf(FILE *fp)
97 {
98         return (wint_t )_filbuf(fp);
99 }
100
101 // convert the carriage return line feed pairs
102 /*
103 int _readcnv(int fn, void *buf, size_t siz  )
104 {
105         char *bufp = (char *)buf;
106         int _bufsiz = siz;
107         int cr = 0;
108         int n;
109
110         n = _read(fn, buf, siz  );
111
112         while (_bufsiz > 0) {
113                 if (*bufp == '\r') 
114                         cr++;
115                 else if ( cr != 0 ) 
116                         *bufp = *(bufp + cr);
117                 bufp++;
118                 _bufsiz--;
119         }
120         return n + cr;
121 }
122  */