X-Git-Url: https://pd.if.org/git/?p=pdclib;a=blobdiff_plain;f=platform%2Fexample%2Ffunctions%2F_PDCLIB%2Fwrite.c;h=67c833f6b9647af82acbe9827c5b0ec56ff3ce71;hp=d2841f694195376ab08ab0419af59fa2a0370cc0;hb=f93d55176e4db9edfb1840054169003bcca4d1fb;hpb=48ec56a384a70f2d7b1293db192e37f6dfaabe1e diff --git a/platform/example/functions/_PDCLIB/write.c b/platform/example/functions/_PDCLIB/write.c index d2841f6..67c833f 100644 --- a/platform/example/functions/_PDCLIB/write.c +++ b/platform/example/functions/_PDCLIB/write.c @@ -7,26 +7,69 @@ */ #include <_PDCLIB_glue.h> +#include #ifndef REGTEST -int write(int, const void *, unsigned int); - -_PDCLIB_size_t _PDCLIB_write( int fd, char const * buffer, _PDCLIB_size_t n ) +int _PDCLIB_write( struct _PDCLIB_file_t * stream, char const * buffer, int n ) { - /* FIXME: Might return value < n, might return -1 on error */ - return write( fd, buffer, n ); + /* CAUTION: We assume ssize_t <=> int here. We do so implicitly so a smart + compiler can throw a warning in case it does not (and you missed this + note). Somewhere we have to cast the return value of write() to that of + _PDCLIB_write() (since the latter cannot use a return type not defined + by the standard). It would perhaps have been syntactically cleaner to + use ssize_t here and make the cast in the return statement, but this + way we don't have to include yet another non-standard header. + */ + int rc; + if ( ( rc = write( stream->handle, buffer, (size_t)n ) ) == -1 ) + { + /* Error encountered */ + stream->status |= _PDCLIB_ERRORFLAG; + /* FIXME: Map the errno of the OS to PDCLib's errno */ + } + return rc; } #endif #ifdef TEST +/* TODO: Work around the following undef */ +#undef SEEK_SET #include <_PDCLIB_test.h> +#include +#include + +#include +#include + +#include + +/* TODO: This uses POSIX system calls for now, should use standard calls + once they are in place. Clumsy sunny-path testing. +*/ int main( void ) { - TESTCASE( NO_TESTDRIVER ); + /* See the code comment at the functions' return statement above. */ + int fd, r; + char * buffer = malloc( 13 ); + TESTCASE( buffer != NULL ); + strcpy( buffer, "Test output\n" ); + /* Writing string to file */ + TESTCASE( ( fd = open( "testfile", O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU ) ) != -1 ); + struct _PDCLIB_file_t file = { fd, { 0, 0 }, buffer, BUFSIZ, 12, 0, 0, NULL }; + TESTCASE( _PDCLIB_write( &file, file.buffer, 12 ) == 12 ); + TESTCASE( close( file.handle ) != -1 ); + /* Reading file back in */ + TESTCASE( ( fd = open( "testfile", O_RDONLY ) ) != -1 ); + memset( buffer, '\0', 13 ); + TESTCASE( ( r = read( file.handle, (void *)buffer, 12 ) ) == 12 ); + TESTCASE( strcmp( buffer, "Test output\n" ) == 0 ); + TESTCASE( close( fd ) != -1 ); + TESTCASE( unlink( "testfile" ) != -1 ); return TEST_RESULTS; } #endif +