:pserver:cvsanon@mok.lvcm.com:/CVS/ReactOS reactos
[reactos.git] / lib / crtdll / stdio / fsopen.c
1 /*
2  * COPYRIGHT:   See COPYING in the top level directory
3  * PROJECT:     ReactOS system libraries
4  * FILE:        lib/crtdll/conio/kbhit.c
5  * PURPOSE:     Checks for keyboard hits
6  * PROGRAMER:   Boudewijn Dekker
7  * UPDATE HISTORY:
8  *              28/12/98: Created
9  */
10 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
11
12 #include <crtdll/sys/types.h>
13 #include <crtdll/stdio.h>
14 #include <crtdll/io.h>
15 #include <crtdll/fcntl.h>
16 #include <crtdll/internal/file.h>
17 #include <crtdll/share.h>
18
19
20 FILE *  __alloc_file(void);
21
22
23 FILE* _fsopen(const char *file, const char *mode, int shflag)
24 {
25   FILE *f;
26   int fd, rw, oflags = 0;
27   char tbchar;
28    
29   int shf;
30
31   if (file == 0)
32     return 0;
33   if (mode == 0)
34     return 0;
35
36   f = __alloc_file();
37   if (f == NULL)
38     return NULL;
39
40   rw = (mode[1] == '+') || (mode[1] && (mode[2] == '+'));
41
42   switch (*mode)
43   {
44   case 'a':
45     oflags = O_CREAT | (rw ? O_RDWR : O_WRONLY);
46     break;
47   case 'r':
48     oflags = rw ? O_RDWR : O_RDONLY;
49     break;
50   case 'w':
51     oflags = O_TRUNC | O_CREAT | (rw ? O_RDWR : O_WRONLY);
52     break;
53   default:
54     return (NULL);
55   }
56   if (mode[1] == '+')
57     tbchar = mode[2];
58   else
59     tbchar = mode[1];
60   if (tbchar == 't')
61     oflags |= O_TEXT;
62   else if (tbchar == 'b')
63     oflags |= O_BINARY;
64   else
65     oflags |= (_fmode & (O_TEXT|O_BINARY));
66
67
68
69   if ( shflag == _SH_DENYNO )
70         shf = _S_IREAD | _S_IWRITE;
71   else if( shflag == _SH_DENYRD )
72         shf =  _S_IWRITE;
73   else if( shflag == _SH_DENYRW )
74         shf =  0;
75   else if( shflag == _SH_DENYWR )
76         shf =  _S_IREAD;
77   else
78         shf = _S_IREAD | _S_IWRITE;
79   
80   fd = _open(file, oflags, shf);
81   if (fd < 0)
82     return NULL;
83
84 // ms crtdll ensures that writes will end up at the end of file in append mode
85 // we just move the file pointer to the end of file initially
86   if (*mode == 'a')
87     lseek(fd, 0, SEEK_END);
88
89   f->_cnt = 0;
90   f->_file = fd;
91   f->_bufsiz = 0;
92   if (rw)
93     f->_flag = _IOREAD | _IOWRT;
94   else if (*mode == 'r')
95     f->_flag = _IOREAD;
96   else
97     f->_flag = _IOWRT;
98
99   f->_base = f->_ptr = NULL;
100   return f;
101 }