]> pd.if.org Git - pdclib/blob - functions/stdio/fclose.c
Minor touches.
[pdclib] / 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 int fclose( struct _PDCLIB_file_t * stream )
18 {
19     struct _PDCLIB_file_t * current = _PDCLIB_filelist;
20     struct _PDCLIB_file_t * previous = NULL;
21     /* Checking that the FILE handle is actually one we had opened before. */
22     while ( current != NULL )
23     {
24         if ( stream == current )
25         {
26             /* Flush buffer */
27             if ( stream->status & _PDCLIB_FWRITE )
28             {
29                 if ( _PDCLIB_flushbuffer( stream ) == EOF )
30                 {
31                     /* Flush failed, errno already set */
32                     return EOF;
33                 }
34             }
35             /* Free buffer */
36             if ( stream->status & _PDCLIB_LIBBUFFER )
37             {
38                 free( stream->buffer );
39             }
40             /* Close handle */
41             _PDCLIB_close( stream->handle );
42             /* Remove stream from list */
43             if ( previous != NULL )
44             {
45                 previous->next = stream->next;
46             }
47             else
48             {
49                 _PDCLIB_filelist = stream->next;
50             }
51             /* Free stream */
52             free( stream );
53             return 0;
54         }
55         previous = current;
56         current = current->next;
57     }
58     _PDCLIB_errno = _PDCLIB_EIO;
59     return -1;
60 }
61
62 #endif
63
64 #ifdef TEST
65 #include <_PDCLIB_test.h>
66
67 int main( void )
68 {
69 #ifndef REGTEST
70     struct _PDCLIB_file_t * file1;
71     struct _PDCLIB_file_t * file2;
72     remove( "testfile1" );
73     remove( "testfile2" );
74     TESTCASE( _PDCLIB_filelist == stdin );
75     TESTCASE( ( file1 = fopen( "testfile1", "w" ) ) != NULL );
76     TESTCASE( _PDCLIB_filelist == file1 );
77     TESTCASE( ( file2 = fopen( "testfile2", "w" ) ) != NULL );
78     TESTCASE( _PDCLIB_filelist == file2 );
79     TESTCASE( fclose( file2 ) == 0 );
80     TESTCASE( _PDCLIB_filelist == file1 );
81     TESTCASE( ( file2 = fopen( "testfile1", "w" ) ) != NULL );
82     TESTCASE( _PDCLIB_filelist == file2 );
83     TESTCASE( fclose( file1 ) == 0 );
84     TESTCASE( _PDCLIB_filelist == file2 );
85     TESTCASE( fclose( file2 ) == 0 );
86     TESTCASE( _PDCLIB_filelist == stdin );
87     remove( "testfile1" );
88     remove( "testfile2" );
89 #else
90     puts( " NOTEST fclose() test driver is PDCLib-specific." );
91 #endif
92     return TEST_RESULTS;
93 }
94
95 #endif
96