]> pd.if.org Git - pdclib.old/blob - functions/stdio/fclose.c
Improved testdrivers.
[pdclib.old] / functions / stdio / fclose.c
1 /* $Id$ */
2
3 /* fclose( FILE * )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 #ifndef REGTEST
13 #include <_PDCLIB_glue.h>
14
15 extern struct _PDCLIB_file_t * _PDCLIB_filelist;
16
17 /* FIXME: Last file not removed from list. */
18 int fclose( struct _PDCLIB_file_t * stream )
19 {
20     struct _PDCLIB_file_t * current = _PDCLIB_filelist;
21     struct _PDCLIB_file_t * previous = NULL;
22     /* Checking that the FILE handle is actually one we had opened before. */
23     while ( current != NULL )
24     {
25         if ( stream == current )
26         {
27             if ( stream->status & _PDCLIB_WROTELAST ) fflush( stream );
28             if ( stream->status & _PDCLIB_LIBBUFFER ) free( stream->buffer );
29             _PDCLIB_close( stream->handle );
30             if ( previous != NULL )
31             {
32                 previous->next = stream->next;
33             }
34             else
35             {
36                 _PDCLIB_filelist = stream->next;
37             }
38             free( stream );
39             return 0;
40         }
41         previous = current;
42         current = current->next;
43     }
44     return -1;
45 }
46
47 #endif
48
49 #ifdef TEST
50 #include <_PDCLIB_test.h>
51
52 int main( void )
53 {
54 #ifndef REGTEST
55     struct _PDCLIB_file_t * file1;
56     struct _PDCLIB_file_t * file2;
57     TESTCASE( _PDCLIB_filelist == NULL );
58     TESTCASE( ( file1 = fopen( "testfile1", "w" ) ) != NULL );
59     TESTCASE( _PDCLIB_filelist == file1 );
60     TESTCASE( ( file2 = fopen( "testfile2", "w" ) ) != NULL );
61     TESTCASE( _PDCLIB_filelist == file2 );
62     TESTCASE( fclose( file2 ) == 0 );
63     TESTCASE( _PDCLIB_filelist == file1 );
64     TESTCASE( ( file2 = fopen( "testfile1", "w" ) ) != NULL );
65     TESTCASE( _PDCLIB_filelist == file2 );
66     TESTCASE( fclose( file1 ) == 0 );
67     TESTCASE( _PDCLIB_filelist == file2 );
68     TESTCASE( fclose( file2 ) == 0 );
69     TESTCASE( _PDCLIB_filelist == NULL );
70     system( "rm testfile1 testfile2" );
71 #else
72     puts( " NOTEST fclose() test driver is PDCLib-specific." );
73 #endif
74     return TEST_RESULTS;
75 }
76
77 #endif