aboutsummaryrefslogtreecommitdiffstats
path: root/src/pdclib/functions/stdio/fread.c
diff options
context:
space:
mode:
authortcsullivan <tullivan99@gmail.com>2018-11-17 13:02:57 -0500
committertcsullivan <tullivan99@gmail.com>2018-11-17 13:02:57 -0500
commitc6ef89664b8c0d7aa85bddd5c7014aa6df82cbe7 (patch)
treed1f9d09412a46bdf4344fe30392455070a72993d /src/pdclib/functions/stdio/fread.c
parentdb38c4b9dac461de0ed75bf6d079dacba1b31bc9 (diff)
added pdclib, removed sash
Diffstat (limited to 'src/pdclib/functions/stdio/fread.c')
-rw-r--r--src/pdclib/functions/stdio/fread.c81
1 files changed, 81 insertions, 0 deletions
diff --git a/src/pdclib/functions/stdio/fread.c b/src/pdclib/functions/stdio/fread.c
new file mode 100644
index 0000000..319e9ba
--- /dev/null
+++ b/src/pdclib/functions/stdio/fread.c
@@ -0,0 +1,81 @@
+/* fwrite( void *, size_t, size_t, FILE * )
+
+ This file is part of the Public Domain C Library (PDCLib).
+ Permission is granted to use, modify, and / or redistribute at will.
+*/
+
+#include <stdio.h>
+#include <string.h>
+
+#ifndef REGTEST
+
+#include "pdclib/_PDCLIB_glue.h"
+
+size_t fread( void * _PDCLIB_restrict ptr, size_t size, size_t nmemb, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
+{
+ char * dest = (char *)ptr;
+ size_t nmemb_i;
+ if ( _PDCLIB_prepread( stream ) == EOF )
+ {
+ return 0;
+ }
+ for ( nmemb_i = 0; nmemb_i < nmemb; ++nmemb_i )
+ {
+ size_t size_i;
+ for ( size_i = 0; size_i < size; ++size_i )
+ {
+ if ( stream->bufidx == stream->bufend )
+ {
+ if ( _PDCLIB_fillbuffer( stream ) == EOF )
+ {
+ /* Could not read requested data */
+ return nmemb_i;
+ }
+ }
+ dest[ nmemb_i * size + size_i ] = stream->buffer[ stream->bufidx++ ];
+ }
+ }
+ return nmemb_i;
+}
+
+#endif
+
+#ifdef TEST
+
+#include "_PDCLIB_test.h"
+
+int main( void )
+{
+ FILE * fh;
+ const char * message = "Testing fwrite()...\n";
+ char buffer[21];
+ buffer[20] = 'x';
+ TESTCASE( ( fh = tmpfile() ) != NULL );
+ /* fwrite() / readback */
+ TESTCASE( fwrite( message, 1, 20, fh ) == 20 );
+ rewind( fh );
+ TESTCASE( fread( buffer, 1, 20, fh ) == 20 );
+ TESTCASE( memcmp( buffer, message, 20 ) == 0 );
+ TESTCASE( buffer[20] == 'x' );
+ /* same, different nmemb / size settings */
+ rewind( fh );
+ TESTCASE( memset( buffer, '\0', 20 ) == buffer );
+ TESTCASE( fwrite( message, 5, 4, fh ) == 4 );
+ rewind( fh );
+ TESTCASE( fread( buffer, 5, 4, fh ) == 4 );
+ TESTCASE( memcmp( buffer, message, 20 ) == 0 );
+ TESTCASE( buffer[20] == 'x' );
+ /* same... */
+ rewind( fh );
+ TESTCASE( memset( buffer, '\0', 20 ) == buffer );
+ TESTCASE( fwrite( message, 20, 1, fh ) == 1 );
+ rewind( fh );
+ TESTCASE( fread( buffer, 20, 1, fh ) == 1 );
+ TESTCASE( memcmp( buffer, message, 20 ) == 0 );
+ TESTCASE( buffer[20] == 'x' );
+ /* Done. */
+ TESTCASE( fclose( fh ) == 0 );
+ return TEST_RESULTS;
+}
+
+#endif