]> pd.if.org Git - pdclib.old/blob - functions/stdio/_PDCLIB_flushbuffer.c
44066d87dbd24099d40fe16ca657f25ef786c858
[pdclib.old] / functions / stdio / _PDCLIB_flushbuffer.c
1 /* _PDCLIB_flushbuffer( struct _PDCLIB_file_t * )\r
2 \r
3    This file is part of the Public Domain C Library (PDCLib).\r
4    Permission is granted to use, modify, and / or redistribute at will.\r
5 */\r
6 \r
7 #include <stdio.h>\r
8 #include <string.h>\r
9 \r
10 #ifndef REGTEST\r
11 #include <_PDCLIB_glue.h>\r
12 #include <_PDCLIB_io.h>\r
13 \r
14 static int flushsubbuffer( FILE * stream, size_t length )\r
15 {\r
16     size_t written = 0;\r
17     int rv = 0;\r
18 \r
19     while( written != length )\r
20     {\r
21         size_t justWrote;\r
22         size_t toWrite = length - written;\r
23         bool res = stream->ops->write( stream->handle, stream->buffer + written,\r
24                               toWrite, &justWrote);\r
25         written += justWrote;\r
26         stream->pos.offset += justWrote;\r
27 \r
28         if (!res)\r
29         {\r
30             stream->status |=_PDCLIB_ERRORFLAG;\r
31             rv = EOF;\r
32             break;\r
33         }\r
34     }\r
35 \r
36     stream->bufidx -= written;\r
37     memmove( stream->buffer, stream->buffer + written, stream->bufidx );\r
38 \r
39     return rv;\r
40 }\r
41 \r
42 #if defined(_PDCLIB_NEED_EOL_TRANSLATION)\r
43 #undef  _PDCLIB_NEED_EOL_TRANSLATION\r
44 #define _PDCLIB_NEED_EOL_TRANSLATION 1\r
45 #else\r
46 #define _PDCLIB_NEED_EOL_TRANSLATION 0\r
47 #endif\r
48 \r
49 int _PDCLIB_flushbuffer( FILE * stream )\r
50 {\r
51     // if a text stream, and this platform needs EOL translation, well...\r
52     if ( ! ( stream->status & _PDCLIB_FBIN ) && _PDCLIB_NEED_EOL_TRANSLATION )\r
53     {\r
54         size_t pos;\r
55         for ( pos = 0; pos < stream->bufidx; pos++ )\r
56         {\r
57             if (stream->buffer[pos] == '\n' ) {\r
58                 if ( stream->bufidx == stream->bufend ) {\r
59                     // buffer is full. Need to print out everything up till now\r
60                     if( flushsubbuffer( stream, pos ) )\r
61                     {\r
62                         return EOF;\r
63                     }\r
64 \r
65                     pos = 0;\r
66                 }\r
67 \r
68                 // we have spare space in buffer. Shift everything 1char and\r
69                 // insert \r\r
70                 memmove( &stream->buffer[pos+1], &stream->buffer[pos], stream->bufidx - pos );\r
71                 stream->buffer[pos] = '\r';\r
72 \r
73                 pos += 2;\r
74                 stream->bufidx++;\r
75             }\r
76         }\r
77     }\r
78 \r
79     return flushsubbuffer( stream, stream->bufidx );\r
80 }\r
81 \r
82 #endif\r
83 \r
84 \r
85 #ifdef TEST\r
86 #include <_PDCLIB_test.h>\r
87 \r
88 int main( void )\r
89 {\r
90     /* Testing covered by ftell.c */\r
91     return TEST_RESULTS;\r
92 }\r
93 \r
94 #endif\r
95 \r