]> git.sur5r.net Git - cc65/blob - libsrc/common/_fopen.c
Removed comment about a cast that is no longer necessary
[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     unsigned char binmode;
19
20     switch (*mode++) {
21         case 'w':
22             binmode = O_WRONLY | O_CREAT | O_TRUNC;
23             break;
24         case 'r':
25             binmode = O_RDONLY;
26             break;
27         case 'a':
28             binmode = O_WRONLY | O_CREAT | O_APPEND;
29             break;
30        default:
31             return 0;  /* invalid char */
32     }
33
34     while (1) {
35         switch (*mode++) {
36             case '+':
37                 /* always to r/w in addition to anything already set */
38                 binmode |= O_RDWR;
39                 break;
40             case 'b':
41                 /* currently ignored */
42                 break;
43             case '\0':
44                 /* end of mode string reached */
45                 return binmode;
46             default:
47                 /* invalid char in mode string */
48                 return 0;
49         }
50     }
51 }
52
53
54
55 FILE* _fopen (const char* name, const char* mode, FILE* f)
56 /* Open the specified file and fill the descriptor values into f */
57 {
58     int           fd;
59     unsigned char binmode;
60
61
62     /* Convert ASCII mode to binary mode */
63     if ((binmode = amode_to_bmode (mode)) == 0) {
64         /* Invalid mode */
65         _errno = EINVAL;
66         return 0;
67     }
68
69     /* Open the file */
70     fd = open (name, binmode);
71     if (fd == -1) {
72         /* Error - _oserror is set */
73         return 0;
74     }
75
76     /* Remember fd, mark the file as opened */
77     f->f_fd    = fd;
78     f->f_flags = _FOPEN;
79
80     /* Return the file descriptor */
81     return f;
82 }
83
84
85