]> pd.if.org Git - pdclib/blob - functions/stdio/fread.c
Comment cleanups.
[pdclib] / functions / stdio / fread.c
1 /* fwrite( void *, size_t, size_t, FILE * )
2
3    This file is part of the Public Domain C Library (PDCLib).
4    Permission is granted to use, modify, and / or redistribute at will.
5 */
6
7 #include <stdio.h>
8
9 #ifndef REGTEST
10
11 #include <_PDCLIB_glue.h>
12
13 #include <stdbool.h>
14 #include <string.h>
15
16 size_t fread( void * _PDCLIB_restrict ptr, size_t size, size_t nmemb, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
17 {
18     if ( _PDCLIB_prepread( stream ) == EOF )
19     {
20         return 0;
21     }
22     char * dest = (char *)ptr;
23     size_t nmemb_i;
24     for ( nmemb_i = 0; nmemb_i < nmemb; ++nmemb_i )
25     {
26         for ( size_t size_i = 0; size_i < size; ++size_i )
27         {
28             if ( stream->bufidx == stream->bufend )
29             {
30                 if ( _PDCLIB_fillbuffer( stream ) == EOF )
31                 {
32                     /* Could not read requested data */
33                     return nmemb_i;
34                 }
35             }
36             dest[ nmemb_i * size + size_i ] = stream->buffer[ stream->bufidx++ ];
37         }
38     }
39     return nmemb_i;
40 }
41
42 #endif
43
44 #ifdef TEST
45 #include <_PDCLIB_test.h>
46
47 int main( void )
48 {
49     FILE * fh;
50     char const * message = "Testing fwrite()...\n";
51     char buffer[21];
52     buffer[20] = 'x';
53     TESTCASE( ( fh = tmpfile() ) != NULL );
54     /* fwrite() / readback */
55     TESTCASE( fwrite( message, 1, 20, fh ) == 20 );
56     rewind( fh );
57     TESTCASE( fread( buffer, 1, 20, fh ) == 20 );
58     TESTCASE( memcmp( buffer, message, 20 ) == 0 );
59     TESTCASE( buffer[20] == 'x' );
60     /* same, different nmemb / size settings */
61     rewind( fh );
62     TESTCASE( memset( buffer, '\0', 20 ) == buffer );
63     TESTCASE( fwrite( message, 5, 4, fh ) == 4 );
64     rewind( fh );
65     TESTCASE( fread( buffer, 5, 4, fh ) == 4 );
66     TESTCASE( memcmp( buffer, message, 20 ) == 0 );
67     TESTCASE( buffer[20] == 'x' );
68     /* same... */
69     rewind( fh );
70     TESTCASE( memset( buffer, '\0', 20 ) == buffer );
71     TESTCASE( fwrite( message, 20, 1, fh ) == 1 );
72     rewind( fh );
73     TESTCASE( fread( buffer, 20, 1, fh ) == 1 );
74     TESTCASE( memcmp( buffer, message, 20 ) == 0 );
75     TESTCASE( buffer[20] == 'x' );
76     /* Done. */
77     TESTCASE( fclose( fh ) == 0 );
78     return TEST_RESULTS;
79 }
80
81 #endif
82