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