5 This file is part of the Public Domain C Library (PDCLib).
6 Permission is granted to use, modify, and / or redistribute at will.
14 #include <_PDCLIB_io.h>
17 extern FILE * _PDCLIB_filelist;
19 int fclose( FILE * stream )
21 FILE * current = _PDCLIB_filelist;
22 FILE * previous = NULL;
23 /* Checking that the FILE handle is actually one we had opened before. */
24 while ( current != NULL )
26 if ( stream == current )
29 if ( stream->status & _PDCLIB_FWRITE )
31 if ( _PDCLIB_flushbuffer( stream ) == EOF )
33 /* Flush failed, errno already set */
39 mtx_destroy( &stream->lock );
42 stream->ops->close(stream->handle);
44 /* Remove stream from list */
45 if ( previous != NULL )
47 previous->next = stream->next;
51 _PDCLIB_filelist = stream->next;
53 /* Delete tmpfile() */
54 if ( stream->status & _PDCLIB_DELONCLOSE )
56 remove( stream->filename );
58 /* Free user buffer (SetVBuf allocated) */
59 if ( stream->status & _PDCLIB_FREEBUFFER )
61 free( stream->buffer );
64 if ( ! ( stream->status & _PDCLIB_STATIC ) )
71 current = current->next;
81 #include <_PDCLIB_test.h>
90 TESTCASE( _PDCLIB_filelist == stdin );
91 TESTCASE( ( file1 = fopen( testfile1, "w" ) ) != NULL );
92 TESTCASE( _PDCLIB_filelist == file1 );
93 TESTCASE( ( file2 = fopen( testfile2, "w" ) ) != NULL );
94 TESTCASE( _PDCLIB_filelist == file2 );
95 TESTCASE( fclose( file2 ) == 0 );
96 TESTCASE( _PDCLIB_filelist == file1 );
97 TESTCASE( ( file2 = fopen( testfile2, "w" ) ) != NULL );
98 TESTCASE( _PDCLIB_filelist == file2 );
99 TESTCASE( fclose( file1 ) == 0 );
100 TESTCASE( _PDCLIB_filelist == file2 );
101 TESTCASE( fclose( file2 ) == 0 );
102 TESTCASE( _PDCLIB_filelist == stdin );
103 TESTCASE( remove( testfile1 ) == 0 );
104 TESTCASE( remove( testfile2 ) == 0 );
106 puts( " NOTEST fclose() test driver is PDCLib-specific." );