Buffered I/O operations use an intermediary buffer managed by the C library. The intermediary buffer stores data to be read or written to a stream (file or device). This mode provides better I/O performance when compared to the non buffered I/O mode because it tends to reduce the number of actual reads and writes.
Since buffered I/O is not synchronous in real time, data may not be actually written in the stream until the intermediary buffer is flushed.
For this reason, when using fread/fwrite in real time systems, one must make sure to flush the I/O buffers or to force the C library to write all the provided data.
There are two ways for doing this
The function fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. The open status of the stream is unaffected. See man pages for more details.
If the fflush function is not available. The following construct ensures the full buffer provided to fwrite is output.
for (;;) { j=fwrite(buffer,1,data_length,output_stream); if (j <= 0) { perror("fwrite error"); goto err; } if (i == j) break; buffer+=j; i-=j; }
| Labels: coding, embedded, howto |
|