update for HEAD-2003091401
[reactos.git] / lib / crtdll / stdio / freopen.c
1 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
2
3 #include <msvcrt/sys/types.h>
4 #include <msvcrt/stdio.h>
5 #include <msvcrt/fcntl.h>
6 #include <msvcrt/io.h>
7 #include <msvcrt/internal/file.h>
8
9
10 /*
11  * @implemented
12  */
13 FILE *freopen(const char *file, const char *mode, FILE *f)
14 {
15   int fd, rw, oflags=0;
16   char tbchar;
17
18   if (file == 0 || mode == 0 || f == 0)
19     return 0;
20
21   rw = (mode[1] == '+');
22
23   fclose(f);
24
25   switch (*mode) {
26   case 'a':
27     oflags = O_CREAT | (rw ? O_RDWR : O_WRONLY);
28     break;
29   case 'r':
30     oflags = rw ? O_RDWR : O_RDONLY;
31     break;
32   case 'w':
33     oflags = O_TRUNC | O_CREAT | (rw ? O_RDWR : O_WRONLY);
34     break;
35   default:
36     return NULL;
37   }
38   if (mode[1] == '+')
39     tbchar = mode[2];
40   else
41     tbchar = mode[1];
42   if (tbchar == 't')
43     oflags |= O_TEXT;
44   else if (tbchar == 'b')
45     oflags |= O_BINARY;
46   else
47     oflags |= (_fmode & (O_TEXT|O_BINARY));
48
49   fd = _open(file, oflags, 0666);
50   if (fd < 0)
51     return NULL;
52
53   if (*mode == 'a')
54     lseek(fd, 0, SEEK_END);
55
56   f->_cnt = 0;
57   f->_file = fd;
58   f->_bufsiz = 0;
59   if (rw)
60     f->_flag = _IOREAD | _IOWRT;
61   else if (*mode == 'r')
62     f->_flag = _IOREAD;
63   else
64     f->_flag = _IOWRT;
65
66   f->_base = f->_ptr = NULL;
67   return f;
68 }