]> pd.if.org Git - pdclib/blob - functions/_PDCLIB/fflush.c
e8c99db75122ae33b17230f1c5b26e4932f96604
[pdclib] / functions / _PDCLIB / fflush.c
1 /* $Id$ */
2
3 /* _PDCLIB_flushbuffer( 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 #include <limits.h>
11 #include <assert.h>
12
13 #include <_PDCLIB_glue.h>
14
15 _PDCLIB_size_t _PDCLIB_flushbuffer( struct _PDCLIB_file_t * stream, _PDCLIB_size_t written, int retries )
16 {
17     _PDCLIB_size_t n = stream->bufidx - written;
18     int count = _PDCLIB_write( stream, stream->buffer + written, ( n <= INT_MAX ? (int)n : INT_MAX ) );
19     written += count; /* if count is -1, we don't need written anyway */
20     switch ( count )
21     {
22         case -1:
23             /* write error */
24             stream->status |= _PDCLIB_ERRORFLAG;
25             /* FIXME: Map host errno to PDCLib errno */
26             return 0;
27         case 0:
28             /* no characters written - retry */
29             if ( retries == _PDCLIB_FLUSH_RETRIES )
30             {
31                 /* max. number of retries without characters being written */
32                 stream->status |= _PDCLIB_ERRORFLAG;
33                 /* FIXME: Set errno */
34                 return 0;
35             }
36             _PDCLIB_FLUSH_RETRY_PREP;
37             return _PDCLIB_flushbuffer( stream, written, retries + 1 );
38         default:
39             /* If the following assert fails, we wrote more characters than
40                available in the buffer. (???)
41             */
42             assert( written <= stream->bufidx );
43             if ( written == stream->bufidx ) 
44             {
45                 /* write complete */
46                 stream->bufidx = 0;
47                 return written;
48             }
49             return _PDCLIB_flushbuffer( stream, written, 0 );
50     }
51 }
52     
53 #ifdef TEST
54 #include <_PDCLIB_test.h>
55
56 int main( void )
57 {
58     TESTCASE( NO_TESTDRIVER );
59     return TEST_RESULTS;
60 }
61
62 #endif
63