]> pd.if.org Git - pdclib/blob - functions/stdio/fopen.c
18b7b3ae4df8e2cf5646bb87fc88fc20bedc8eba
[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 #include <string.h>
15 #include <errno.h>
16
17 extern struct _PDCLIB_file_t * _PDCLIB_filelist;
18
19 FILE * fopen( const char * _PDCLIB_restrict filename, 
20               const char * _PDCLIB_restrict mode )
21 {
22     int imode = _PDCLIB_filemode( mode );
23     _PDCLIB_fd_t fd = _PDCLIB_open( filename, imode );
24     if(fd == _PDCLIB_NOHANDLE) {
25         return NULL;
26     }
27
28     FILE * f = _PDCLIB_fdopen( fd, imode, filename );
29     if(!f) {
30         int saveErrno = errno;
31         _PDCLIB_close( fd );
32         errno = saveErrno;
33     }
34     return f;
35 }
36
37 #endif
38
39 #ifdef TEST
40 #include <_PDCLIB_test.h>
41
42 int main( void )
43 {
44     /* Some of the tests are not executed for regression tests, as the libc on
45        my system is at once less forgiving (segfaults on mode NULL) and more
46        forgiving (accepts undefined modes).
47     */
48     FILE * fh;
49     remove( testfile );
50     TESTCASE_NOREG( fopen( NULL, NULL ) == NULL );
51     TESTCASE( fopen( NULL, "w" ) == NULL );
52     TESTCASE_NOREG( fopen( "", NULL ) == NULL );
53     TESTCASE( fopen( "", "w" ) == NULL );
54     TESTCASE( fopen( "foo", "" ) == NULL );
55     TESTCASE_NOREG( fopen( testfile, "wq" ) == NULL ); /* Undefined mode */
56     TESTCASE_NOREG( fopen( testfile, "wr" ) == NULL ); /* Undefined mode */
57     TESTCASE( ( fh = fopen( testfile, "w" ) ) != NULL );
58     TESTCASE( fclose( fh ) == 0 );
59     TESTCASE( remove( testfile ) == 0 );
60     return TEST_RESULTS;
61 }
62
63 #endif