]> pd.if.org Git - pdclib/blob - functions/stdio/fopen.c
Porting current working set from CVS.
[pdclib] / functions / stdio / fopen.c
1 /* $Id$ */
2
3 /* Release $Name$ */
4
5 /* fopen( const char *, const char * )
6
7    This file is part of the Public Domain C Library (PDCLib).
8    Permission is granted to use, modify, and / or redistribute at will.
9 */
10
11 #include <stdio.h>
12 #include <stdlib.h>
13
14 #ifndef REGTEST
15 #include <_PDCLIB_glue.h>
16
17 static const FILE * _PDCLIB_filelist = NULL;
18
19 static int filemode( char const * const mode )
20 {
21     int rc = 0;
22     switch ( mode[0] )
23     {
24         case 'r':
25             rc |= _PDCLIB_FREAD;
26             break;
27         case 'w':
28             rc |= _PDCLIB_FWRITE;
29             break;
30         case 'a':
31             rc |= _PDCLIB_FAPPEND;
32             break;
33         default:
34             return -1;
35     }
36     for ( size_t i = 1; i < 4; ++i )
37     {
38         switch ( mode[1] )
39         {
40             case '+':
41                 if ( rc & _PDCLIB_FRW ) return -1;
42                 rc |= _PDCLIB_FRW;
43                 break;
44             case 'b':
45                 if ( rc & _PDCLIB_FBIN ) return -1;
46                 rc |= _PDCLIB_FBIN;
47                 break;
48             case '\0':
49                 return rc;
50             default:
51                 return -1;
52         }
53     }
54     return -1;
55 }
56
57 FILE * fopen( const char * _PDCLIB_restrict filename, const char * _PDCLIB_restrict mode )
58 {
59     FILE * rc;
60     if ( mode == NULL || filename == NULL || filename[0] == '\0' )
61     {
62         return NULL;
63     }
64     if ( ( rc = calloc( 1, sizeof( FILE ) ) ) == NULL ) return rc; /* no space for another FILE */
65     if ( ( rc->status = filemode( mode ) ) == -1 ) goto fail; /* invalid mode given */
66     if ( ( rc->handle = _PDCLIB_open( filename, rc->status ) ) == -1 ) goto fail; /* OS "open" failed */
67     rc->next = _PDCLIB_filelist;
68     _PDCLIB_filelist = rc;
69     /* TODO: Continue here: Set up PDCLib FILE contents */
70     return rc;
71 fail:
72     free( rc );
73     return NULL;
74 }
75
76 #endif
77
78 #ifdef TEST
79 #include <_PDCLIB_test.h>
80
81 int main( void )
82 {
83     TESTCASE( NO_TESTDRIVER );
84     return TEST_RESULTS;
85 }
86
87 #endif