]> git.sur5r.net Git - cc65/blob - libsrc/common/_fopen.c
Copy TGI drivers into main lib dir
[cc65] / libsrc / common / _fopen.c
1 /*
2  * _fopen.c
3  *
4  * Ullrich von bassewitz, 17.06.1997
5  */
6
7
8
9 #include <fcntl.h>
10 #include <errno.h>
11 #include "_file.h"
12
13
14
15 static unsigned char amode_to_bmode (const char* mode)
16 /* Convert ASCII mode (like for fopen) to binary mode (for open) */
17 {
18     char          c;
19     char          flag = 0;
20     unsigned char binmode = 0;
21
22     c = *mode++;
23     switch(c) {
24         case 'w':
25             binmode = O_WRONLY;
26             break;
27         case 'r':
28             binmode = O_RDONLY;
29             break;
30         case 'a':
31             binmode = O_WRONLY | O_APPEND;
32             break;
33        default:
34             return 0;  /* invalid char */
35     }
36
37     while (c = *mode++) {
38         switch(c) {
39             case '+':
40                 binmode = (binmode & ~15) | O_RDWR;
41                 break;
42             case 'b':
43                 /* currently ignored */
44                 break;
45             default:
46                 return 0;  /* invalid char */
47         }
48     }
49     return binmode;
50 }
51
52
53
54 FILE* _fopen (const char* name, const char* mode, FILE* f)
55 /* Open the specified file and fill the descriptor values into f */
56 {
57     int           fd;
58     unsigned char binmode;
59
60
61     /* Convert ASCII mode to binary mode */
62     if ((binmode = amode_to_bmode (mode)) == 0) {
63         /* Invalid mode */
64         _errno = EINVAL;
65         return 0;
66     }
67
68     /* Open the file */
69     fd = open (name, binmode);
70     if (fd == -1) {
71         /* Error - _oserror is set */
72         return 0;
73     }
74
75     /* Remember fd, mark the file as opened */
76     f->f_fd    = fd;
77     f->f_flags = _FOPEN;
78
79     /* Return the file descriptor */
80     return f;
81 }
82
83
84