3 This file is part of the Public Domain C Library (PDCLib).
4 Permission is granted to use, modify, and / or redistribute at will.
12 #include <_PDCLIB_io.h>
15 extern FILE * _PDCLIB_filelist;
17 int fclose( FILE * stream )
19 FILE * current = _PDCLIB_filelist;
20 FILE * previous = NULL;
21 /* Checking that the FILE handle is actually one we had opened before. */
22 while ( current != NULL )
24 if ( stream == current )
27 if ( stream->status & _PDCLIB_FWRITE )
29 if ( _PDCLIB_flushbuffer( stream ) == EOF )
31 /* Flush failed, errno already set */
37 mtx_destroy( &stream->lock );
40 stream->ops->close(stream->handle);
42 /* Remove stream from list */
43 if ( previous != NULL )
45 previous->next = stream->next;
49 _PDCLIB_filelist = stream->next;
51 /* Delete tmpfile() */
52 if ( stream->status & _PDCLIB_DELONCLOSE )
54 remove( stream->filename );
56 /* Free user buffer (SetVBuf allocated) */
57 if ( stream->status & _PDCLIB_FREEBUFFER )
59 free( stream->buffer );
62 if ( ! ( stream->status & _PDCLIB_STATIC ) )
69 current = current->next;
79 #include <_PDCLIB_test.h>
88 TESTCASE( _PDCLIB_filelist == stdin );
89 TESTCASE( ( file1 = fopen( testfile1, "w" ) ) != NULL );
90 TESTCASE( _PDCLIB_filelist == file1 );
91 TESTCASE( ( file2 = fopen( testfile2, "w" ) ) != NULL );
92 TESTCASE( _PDCLIB_filelist == file2 );
93 TESTCASE( fclose( file2 ) == 0 );
94 TESTCASE( _PDCLIB_filelist == file1 );
95 TESTCASE( ( file2 = fopen( testfile2, "w" ) ) != NULL );
96 TESTCASE( _PDCLIB_filelist == file2 );
97 TESTCASE( fclose( file1 ) == 0 );
98 TESTCASE( _PDCLIB_filelist == file2 );
99 TESTCASE( fclose( file2 ) == 0 );
100 TESTCASE( _PDCLIB_filelist == stdin );
101 TESTCASE( remove( testfile1 ) == 0 );
102 TESTCASE( remove( testfile2 ) == 0 );
104 puts( " NOTEST fclose() test driver is PDCLib-specific." );