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