X-Git-Url: https://pd.if.org/git/?a=blobdiff_plain;f=functions%2Fstdio%2Ffread.c;h=9695db43bb1f43a833fb5a02447dce1dfe07886f;hb=3309ec3ad8a5db735eaa2de7f5dc6a331d8e7319;hp=83bc3b7e6d0eb2f5dd5e571e393bcdfb46f5a69d;hpb=52e702f02142dc34a476f01ca6bf8257cc9bc7e4;p=pdclib.old diff --git a/functions/stdio/fread.c b/functions/stdio/fread.c index 83bc3b7..9695db4 100644 --- a/functions/stdio/fread.c +++ b/functions/stdio/fread.c @@ -1,19 +1,49 @@ /* $Id$ */ -/* fread( void *, size_t, size_t, FILE * ) +/* 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 -#include <_PDCLIB_glue.h> #ifndef REGTEST +#include <_PDCLIB_io.h> -size_t fread( void * _PDCLIB_restrict ptr, size_t size, size_t nmemb, struct _PDCLIB_file_t * _PDCLIB_restrict stream ) +#include +#include + +size_t _PDCLIB_fread_unlocked( + void * _PDCLIB_restrict ptr, + size_t size, size_t nmemb, + FILE * _PDCLIB_restrict stream +) { - return _PDCLIB_read( stream->handle, ptr, size * nmemb ); + if ( _PDCLIB_prepread( stream ) == EOF ) + { + return 0; + } + char * dest = (char *)ptr; + size_t nmemb_i; + for ( nmemb_i = 0; nmemb_i < nmemb; ++nmemb_i ) + { + size_t numread = _PDCLIB_getchars( &dest[ nmemb_i * size ], size, EOF, + stream ); + if( numread != size ) + break; + } + return nmemb_i; +} + +size_t fread( void * _PDCLIB_restrict ptr, + size_t size, size_t nmemb, + FILE * _PDCLIB_restrict stream ) +{ + _PDCLIB_flockfile( stream ); + size_t r = _PDCLIB_fread_unlocked( ptr, size, nmemb, stream ); + _PDCLIB_funlockfile( stream ); + return r; } #endif @@ -23,8 +53,37 @@ size_t fread( void * _PDCLIB_restrict ptr, size_t size, size_t nmemb, struct _PD int main( void ) { - /* Testing handled by fwrite(). */ + FILE * fh; + char const * 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 +