]> pd.if.org Git - pdclib/blob - platform/example/functions/_PDCLIB/write.c
21479080f40dff7550ee15d7d2d349f85cdf884e
[pdclib] / platform / example / functions / _PDCLIB / write.c
1 /* $Id$ */
2
3 /* _PDCLIB_write( _PDCLIB_fd_t, char const *, _PDCLIB_size_t )
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 <_PDCLIB_glue.h>
10 #include <unistd.h>
11
12 #ifndef REGTEST
13
14 int _PDCLIB_write( struct _PDCLIB_file_t * stream, char const * buffer, int n )
15 {
16     /* CAUTION: We assume ssize_t <=> int here. We do so implicitly so a smart
17        compiler can throw a warning in case it does not (and you missed this
18        note). Somewhere we have to cast the return value of write() to that of
19        _PDCLIB_write() (since the latter cannot use a return type not defined
20        by the standard). It would perhaps have been syntactically cleaner to
21        use ssize_t here and make the cast in the return statement, but this
22        way we don't have to include yet another non-standard header.
23     */
24     int rc;
25     if ( ( rc = write( stream->handle, buffer, (size_t)n ) ) == -1 )
26     {
27         /* Error encountered */
28         stream->status |= _PDCLIB_ERRORFLAG;
29         /* FIXME: Map the errno of the OS to PDCLib's errno */
30     }
31     return rc;
32 }
33
34 #endif
35
36 #ifdef TEST
37 /* TODO: Work around the following undef */
38 #undef SEEK_SET
39 #include <_PDCLIB_test.h>
40
41 #include <stdlib.h>
42 #include <string.h>
43
44 #include <sys/stat.h>
45 #include <fcntl.h>
46
47 #include <errno.h>
48
49 /* TODO: This uses POSIX system calls for now, should use standard calls
50    once they are in place. Clumsy sunny-path testing.
51 */
52 int main( void )
53 {
54     /* See the code comment at the functions' return statement above. */
55     int fd, r;
56     char * buffer = malloc( 13 );
57     TESTCASE( buffer != NULL );
58     strcpy( buffer, "Test output\n" );
59     /* Writing string to file */
60     TESTCASE( ( fd = open( "testfile", O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU ) ) != -1 );
61     struct _PDCLIB_file_t file = { fd, { 0, 0 }, buffer, BUFSIZ, 12, 0, 0, NULL, NULL };
62     TESTCASE( _PDCLIB_write( &file, file.buffer, 12 ) == 12 );
63     TESTCASE( close( file.handle ) != -1 );
64     /* Reading file back in */
65     TESTCASE( ( fd = open( "testfile", O_RDONLY ) ) != -1 );
66     memset( buffer, '\0', 13 );
67     TESTCASE( ( r = read( file.handle, (void *)buffer, 12 ) ) == 12 );
68     TESTCASE( strcmp( buffer, "Test output\n" ) == 0 );
69     TESTCASE( close( fd ) != -1 );
70     TESTCASE( unlink( "testfile" ) != -1 );
71     return TEST_RESULTS;
72 }
73
74 #endif
75