]> pd.if.org Git - pdclib.old/blob - functions/stdio/fclose.c
Added fclose().
[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 = current->next;
33             }
34             else
35             {
36                 _PDCLIB_filelist = current->next;
37             }
38             return 0;
39         }
40         previous = current;
41         current = current->next;
42     }
43     return -1;
44 }
45
46 #endif
47
48 #ifdef TEST
49 #include <_PDCLIB_test.h>
50
51 int main( void )
52 {
53     /* FIXME: This is basically fopen() checking. Flushing and buffer-freeing is not checked. */
54     struct _PDCLIB_file_t * file1;
55     struct _PDCLIB_file_t * file2;
56     TESTCASE( _PDCLIB_filelist == NULL );
57     TESTCASE( ( file1 = fopen( "testfile1", "w" ) ) != NULL );
58     TESTCASE( _PDCLIB_filelist == file1 );
59     TESTCASE( ( file2 = fopen( "testfile2", "w" ) ) != NULL );
60     TESTCASE( _PDCLIB_filelist == file2 );
61     TESTCASE( fclose( file2 ) == 0 );
62     TESTCASE( _PDCLIB_filelist == file1 );
63     TESTCASE( ( file2 = fopen( "testfile1", "w" ) ) != NULL );
64     TESTCASE( _PDCLIB_filelist == file2 );
65     TESTCASE( fclose( file1 ) == 0 );
66     TESTCASE( _PDCLIB_filelist == file2 );
67     TESTCASE( fclose( file2 ) == 0 );
68     TESTCASE( _PDCLIB_filelist == NULL );
69     system( "rm testfile1 testfile2" );
70     return TEST_RESULTS;
71 }
72
73 #endif