3 /* freopen( const char *, const char *, FILE * )
5 This file is part of the Public Domain C Library (PDCLib).
6 Permission is granted to use, modify, and / or redistribute at will.
13 #include <_PDCLIB_glue.h>
17 struct _PDCLIB_file_t * freopen(
18 const char * _PDCLIB_restrict filename,
19 const char * _PDCLIB_restrict mode,
20 struct _PDCLIB_file_t * _PDCLIB_restrict stream )
24 unsigned int status = stream->status & ( _IONBF | _IOLBF | _IOFBF | _PDCLIB_FREEBUFFER | _PDCLIB_DELONCLOSE );
25 /* TODO: This function can change wide orientation of a stream */
26 if ( stream->status & _PDCLIB_FWRITE )
28 _PDCLIB_flushbuffer( stream );
30 if ( ( filename == NULL ) && ( stream->filename == NULL ) )
32 /* TODO: Special handling for mode changes on std-streams */
33 funlockfile( stream );
36 _PDCLIB_close( stream->handle );
37 /* TODO: It is not nice to do this on a stream we just closed.
38 It does not matter with the current implementation of clearerr(),
39 but it might start to matter if someone replaced that implementation.
42 /* The new filename might not fit the old buffer */
43 if ( filename == NULL )
45 /* Use previous filename */
46 filename = stream->filename;
48 else if ( ( stream->filename != NULL ) && ( strlen( stream->filename ) >= strlen( filename ) ) )
50 /* Copy new filename into existing buffer */
51 strcpy( stream->filename, filename );
55 /* Allocate new buffer */
56 if ( ( stream->filename = (char *)malloc( strlen( filename ) ) ) == NULL )
58 funlockfile( stream );
61 strcpy( stream->filename, filename );
63 if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
65 funlockfile( stream );
68 if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
70 funlockfile( stream );
73 /* Re-add the flags we saved above */
74 stream->status |= status;
78 /* TODO: Setting mbstate */
79 if ( ( stream->handle = _PDCLIB_open( filename, stream->status ) ) == _PDCLIB_NOHANDLE )
81 funlockfile( stream );
84 funlockfile( stream );
91 #include <_PDCLIB_test.h>
97 TESTCASE( ( fin = fopen( testfile1, "wb+" ) ) != NULL );
98 TESTCASE( fputc( 'x', fin ) == 'x' );
99 TESTCASE( fclose( fin ) == 0 );
100 TESTCASE( ( fin = freopen( testfile1, "rb", stdin ) ) != NULL );
101 TESTCASE( getchar() == 'x' );
103 TESTCASE( ( fout = freopen( testfile2, "wb+", stdout ) ) != NULL );
104 TESTCASE( putchar( 'x' ) == 'x' );
106 TESTCASE( fgetc( fout ) == 'x' );
108 TESTCASE( fclose( fin ) == 0 );
109 TESTCASE( fclose( fout ) == 0 );
110 TESTCASE( remove( testfile1 ) == 0 );
111 TESTCASE( remove( testfile2 ) == 0 );