]> pd.if.org Git - pdclib.old/blob - functions/stdio/fwrite.c
fwrite: output line buffered content as we go along
[pdclib.old] / functions / stdio / fwrite.c
1 /* $Id$ */
2
3 /* fwrite( const 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 #include <_PDCLIB_io.h>
13 #include <_PDCLIB_glue.h>
14
15 #include <stdbool.h>
16 #include <string.h>
17
18 size_t _PDCLIB_fwrite_unlocked( const void *restrict vptr,
19                size_t size, size_t nmemb,
20                FILE * _PDCLIB_restrict stream )
21 {
22     if ( _PDCLIB_prepwrite( stream ) == EOF )
23     {
24         return 0;
25     }
26
27     const char *restrict ptr = vptr;
28     size_t nmemb_i;
29     for ( nmemb_i = 0; nmemb_i < nmemb; ++nmemb_i )
30     {
31         for ( size_t size_i = 0; size_i < size; ++size_i )
32         {
33             char c = ptr[ nmemb_i * size + size_i ];
34             stream->buffer[ stream->bufidx++ ] = c;
35
36             if ( stream->bufidx == stream->bufsize || ( c == '\n' && stream->status & _IOLBF ) )
37             {
38                 if ( _PDCLIB_flushbuffer( stream ) == EOF )
39                 {
40                     /* Returning number of objects completely buffered */
41                     return nmemb_i;
42                 }
43             }
44         }
45
46         if ( stream->status & _IONBF )
47         {
48             if ( _PDCLIB_flushbuffer( stream ) == EOF )
49             {
50                 /* Returning number of objects completely buffered */
51                 return nmemb_i;
52             }
53         }
54     }
55     return nmemb_i;
56 }
57
58 size_t fwrite( const void * _PDCLIB_restrict ptr,
59                size_t size, size_t nmemb,
60                FILE * _PDCLIB_restrict stream )
61 {
62     _PDCLIB_flockfile( stream );
63     size_t r = _PDCLIB_fwrite_unlocked( ptr, size, nmemb, stream );
64     _PDCLIB_funlockfile( stream );
65     return r;
66 }
67
68 #endif
69
70 #ifdef TEST
71 #include <_PDCLIB_test.h>
72
73 int main( void )
74 {
75     /* Testing covered by fread(). */
76     return TEST_RESULTS;
77 }
78
79 #endif
80