update for HEAD-2003021201
[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 FILE *freopen(const char *file, const char *mode, FILE *f)
11 {
12   int fd, rw, oflags=0;
13   char tbchar;
14
15   if (file == 0 || mode == 0 || f == 0)
16     return 0;
17
18   rw = (mode[1] == '+');
19
20   fclose(f);
21
22   switch (*mode) {
23   case 'a':
24     oflags = O_CREAT | (rw ? O_RDWR : O_WRONLY);
25     break;
26   case 'r':
27     oflags = rw ? O_RDWR : O_RDONLY;
28     break;
29   case 'w':
30     oflags = O_TRUNC | O_CREAT | (rw ? O_RDWR : O_WRONLY);
31     break;
32   default:
33     return NULL;
34   }
35   if (mode[1] == '+')
36     tbchar = mode[2];
37   else
38     tbchar = mode[1];
39   if (tbchar == 't')
40     oflags |= O_TEXT;
41   else if (tbchar == 'b')
42     oflags |= O_BINARY;
43   else
44     oflags |= (_fmode & (O_TEXT|O_BINARY));
45
46   fd = _open(file, oflags, 0666);
47   if (fd < 0)
48     return NULL;
49
50   if (*mode == 'a')
51     lseek(fd, 0, SEEK_END);
52
53   f->_cnt = 0;
54   f->_file = fd;
55   f->_bufsiz = 0;
56   if (rw)
57     f->_flag = _IOREAD | _IOWRT;
58   else if (*mode == 'r')
59     f->_flag = _IOREAD;
60   else
61     f->_flag = _IOWRT;
62
63   f->_base = f->_ptr = NULL;
64   return f;
65 }