- if ( stream->status & _PDCLIB_WROTELAST ) fflush( stream );
- if ( stream->status & _PDCLIB_LIBBUFFER ) free( stream->buffer );
- _PDCLIB_close( stream->handle );
+ /* Flush buffer */
+ if ( stream->status & _PDCLIB_FWRITE )
+ {
+ if ( _PDCLIB_flushbuffer( stream ) == EOF )
+ {
+ /* Flush failed, errno already set */
+ return EOF;
+ }
+ }
+
+ /* Release mutex*/
+ mtx_destroy( &stream->lock );
+
+ /* Close handle */
+ stream->ops->close(stream->handle);
+
+ /* Remove stream from list */