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