]> pd.if.org Git - pdclib/blob - platform/example/functions/_PDCLIB/open.c
First working testdriver.
[pdclib] / platform / example / functions / _PDCLIB / open.c
1 /* $Id$ */
2
3 /* _PDCLIB_open( char const * const, int )
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 /* This is an example implementation of _PDCLIB_open() fit for use with POSIX
10    kernels.
11 */
12
13 #include <stdio.h>
14
15 #ifndef REGTEST
16 #include <_PDCLIB_glue.h>
17
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22
23 _PDCLIB_fd_t _PDCLIB_open( char const * const filename, unsigned int mode )
24 {
25     /* FIXME: THIS IS NOT TO BE USED OUT-OF-THE-BOX.
26        It is a proof-of-concept implementation. E.g. a stream may only be fully
27        buffered IF IT CAN BE DETERMINED NOT TO REFER TO AN INTERACTIVE DEVICE.
28        This logic is not represented here, as this is the EXAMPLE platform, and
29        actual platform overlays may differ widely. Another point is the value
30        for permissions being hardcoded to 0664 for file creations.
31     */
32     int osmode;
33     switch ( mode & ~_PDCLIB_FBIN )
34     {
35         case _PDCLIB_FREAD: /* "r" */
36             osmode = O_RDONLY;
37             break;
38         case _PDCLIB_FWRITE: /* "w" */
39             osmode = O_WRONLY | O_CREAT | O_TRUNC;
40             break;
41         case _PDCLIB_FAPPEND: /* "a" */
42             osmode = O_APPEND | O_CREAT;
43             break;
44         case _PDCLIB_FREAD | _PDCLIB_FRW: /* "r+" */
45             osmode = O_RDWR;
46             break;
47         case _PDCLIB_FWRITE | _PDCLIB_FRW: /* "w+" */
48             osmode = O_RDWR | O_CREAT | O_TRUNC;
49             break;
50         case _PDCLIB_FAPPEND | _PDCLIB_FRW: /* "a+" */
51             osmode = O_RDWR | O_APPEND | O_CREAT;
52             break;
53         default: /* Invalid mode */
54             return -1;
55     }
56     if ( osmode & O_CREAT )
57     {
58         return open( filename, osmode, S_IRUSR | S_IWUSR );
59     }
60     else
61     {
62         return open( filename, osmode );
63     }
64 }
65
66 #endif
67
68 #ifdef TEST
69 #include <_PDCLIB_test.h>
70
71 #include <stdlib.h>
72
73 int main( void )
74 {
75     /* This testdriver assumes POSIX, i.e. _PDCLIB_fd_t being int and being
76        incremented by one on each successful open.
77     */
78     _PDCLIB_fd_t fh;
79     TESTCASE( _PDCLIB_open( "testfile2", _PDCLIB_FREAD ) == _PDCLIB_NOHANDLE );
80     TESTCASE( ( fh = _PDCLIB_open( "testfile1", _PDCLIB_FWRITE ) ) != _PDCLIB_NOHANDLE );
81     TESTCASE( write( fh, "test", 4 ) == 4 );
82     TESTCASE( close( fh ) == 0 );
83     TESTCASE( _PDCLIB_open( "testfile1", _PDCLIB_FREAD ) != _PDCLIB_NOHANDLE );
84     system( "rm testfile1" );
85     return TEST_RESULTS;
86 }
87
88 #endif