]> pd.if.org Git - pdclib.old/blob - functions/stdio/fread.c
f1ab3a9adeb84745336a2043e8d0d4c8e95a8882
[pdclib.old] / 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_unlocked( void * _PDCLIB_restrict ptr, 
19                        size_t size, size_t nmemb, 
20                        struct _PDCLIB_file_t * _PDCLIB_restrict stream )
21 {
22     if ( _PDCLIB_prepread( stream ) == EOF )
23     {
24         return 0;
25     }
26     char * dest = (char *)ptr;
27     size_t nmemb_i;
28     for ( nmemb_i = 0; nmemb_i < nmemb; ++nmemb_i )
29     {
30         size_t numread = _PDCLIB_getchars( &dest[ nmemb_i * size ], size, EOF, 
31                                            stream );
32         if( numread != size )
33             break;
34     }
35     return nmemb_i;
36 }
37
38 size_t fread( void * _PDCLIB_restrict ptr, 
39               size_t size, size_t nmemb, 
40               struct _PDCLIB_file_t * _PDCLIB_restrict stream )
41 {
42     flockfile( stream );
43     size_t r = fread_unlocked( ptr, size, nmemb, stream );
44     funlockfile( stream );
45     return r;
46 }
47
48 #endif
49
50 #ifdef TEST
51 #include <_PDCLIB_test.h>
52
53 int main( void )
54 {
55     FILE * fh;
56     char const * message = "Testing fwrite()...\n";
57     char buffer[21];
58     buffer[20] = 'x';
59     TESTCASE( ( fh = tmpfile() ) != NULL );
60     /* fwrite() / readback */
61     TESTCASE( fwrite( message, 1, 20, fh ) == 20 );
62     rewind( fh );
63     TESTCASE( fread( buffer, 1, 20, fh ) == 20 );
64     TESTCASE( memcmp( buffer, message, 20 ) == 0 );
65     TESTCASE( buffer[20] == 'x' );
66     /* same, different nmemb / size settings */
67     rewind( fh );
68     TESTCASE( memset( buffer, '\0', 20 ) == buffer );
69     TESTCASE( fwrite( message, 5, 4, fh ) == 4 );
70     rewind( fh );
71     TESTCASE( fread( buffer, 5, 4, fh ) == 4 );
72     TESTCASE( memcmp( buffer, message, 20 ) == 0 );
73     TESTCASE( buffer[20] == 'x' );
74     /* same... */
75     rewind( fh );
76     TESTCASE( memset( buffer, '\0', 20 ) == buffer );
77     TESTCASE( fwrite( message, 20, 1, fh ) == 1 );
78     rewind( fh );
79     TESTCASE( fread( buffer, 20, 1, fh ) == 1 );
80     TESTCASE( memcmp( buffer, message, 20 ) == 0 );
81     TESTCASE( buffer[20] == 'x' );
82     /* Done. */
83     TESTCASE( fclose( fh ) == 0 );
84     return TEST_RESULTS;
85 }
86
87 #endif
88