Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alexbevi
GitHub Repository: alexbevi/BizHawk
Path: blob/master/waterbox/libc/functions/stdio/fread.c
2 views
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
#include "_PDCLIB_io.h"
11
12
#include <stdbool.h>
13
#include <string.h>
14
15
size_t _PDCLIB_fread_unlocked(
16
void * _PDCLIB_restrict ptr,
17
size_t size, size_t nmemb,
18
FILE * _PDCLIB_restrict stream
19
)
20
{
21
if ( _PDCLIB_prepread( stream ) == EOF )
22
{
23
return 0;
24
}
25
char * dest = (char *)ptr;
26
size_t nmemb_i;
27
for ( nmemb_i = 0; nmemb_i < nmemb; ++nmemb_i )
28
{
29
size_t numread = _PDCLIB_getchars( &dest[ nmemb_i * size ], size, EOF,
30
stream );
31
if( numread != size )
32
break;
33
}
34
return nmemb_i;
35
}
36
37
size_t fread( void * _PDCLIB_restrict ptr,
38
size_t size, size_t nmemb,
39
FILE * _PDCLIB_restrict stream )
40
{
41
_PDCLIB_flockfile( stream );
42
size_t r = _PDCLIB_fread_unlocked( ptr, size, nmemb, stream );
43
_PDCLIB_funlockfile( stream );
44
return r;
45
}
46
47
#endif
48
49
#ifdef TEST
50
#include "_PDCLIB_test.h"
51
52
int main( void )
53
{
54
FILE * fh;
55
char const * message = "Testing fwrite()...\n";
56
char buffer[21];
57
buffer[20] = 'x';
58
TESTCASE( ( fh = tmpfile() ) != NULL );
59
/* fwrite() / readback */
60
TESTCASE( fwrite( message, 1, 20, fh ) == 20 );
61
rewind( fh );
62
TESTCASE( fread( buffer, 1, 20, fh ) == 20 );
63
TESTCASE( memcmp( buffer, message, 20 ) == 0 );
64
TESTCASE( buffer[20] == 'x' );
65
/* same, different nmemb / size settings */
66
rewind( fh );
67
TESTCASE( memset( buffer, '\0', 20 ) == buffer );
68
TESTCASE( fwrite( message, 5, 4, fh ) == 4 );
69
rewind( fh );
70
TESTCASE( fread( buffer, 5, 4, fh ) == 4 );
71
TESTCASE( memcmp( buffer, message, 20 ) == 0 );
72
TESTCASE( buffer[20] == 'x' );
73
/* same... */
74
rewind( fh );
75
TESTCASE( memset( buffer, '\0', 20 ) == buffer );
76
TESTCASE( fwrite( message, 20, 1, fh ) == 1 );
77
rewind( fh );
78
TESTCASE( fread( buffer, 20, 1, fh ) == 1 );
79
TESTCASE( memcmp( buffer, message, 20 ) == 0 );
80
TESTCASE( buffer[20] == 'x' );
81
/* Done. */
82
TESTCASE( fclose( fh ) == 0 );
83
return TEST_RESULTS;
84
}
85
86
#endif
87
88
89