]> pd.if.org Git - pdclib/blobdiff - platform/example/functions/_PDCLIB/write.c
Intermediate work, checked in for safekeeping as I pick up working on this again.
[pdclib] / platform / example / functions / _PDCLIB / write.c
index d2841f694195376ab08ab0419af59fa2a0370cc0..67c833f6b9647af82acbe9827c5b0ec56ff3ce71 100644 (file)
@@ -7,26 +7,69 @@
 */
 
 #include <_PDCLIB_glue.h>
+#include <unistd.h>
 
 #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 <stdlib.h>
+#include <string.h>
+
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#include <errno.h>
+
+/* 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
+