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( const char * _PDCLIB_restrict filename, const char * _PDCLIB_restrict mode, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
19 unsigned int status = stream->status & ( _IONBF | _IOLBF | _IOFBF | _PDCLIB_FREEBUFFER | _PDCLIB_DELONCLOSE );
20 /* TODO: This function can change wide orientation of a stream */
21 if ( stream->status & _PDCLIB_FWRITE )
23 _PDCLIB_flushbuffer( stream );
25 if ( ( filename == NULL ) && ( stream->filename == NULL ) )
27 /* TODO: Special handling for mode changes on std-streams */
30 _PDCLIB_close( stream->handle );
31 /* TODO: It is not nice to do this on a stream we just closed.
32 It does not matter with the current implementation of clearerr(),
33 but it might start to matter if someone replaced that implementation.
36 /* The new filename might not fit the old buffer */
37 if ( filename == NULL )
39 /* Use previous filename */
40 filename = stream->filename;
42 else if ( ( stream->filename != NULL ) && ( strlen( stream->filename ) >= strlen( filename ) ) )
44 /* Copy new filename into existing buffer */
45 strcpy( stream->filename, filename );
49 /* Allocate new buffer */
50 if ( ( stream->filename = (char *)malloc( strlen( filename ) ) ) == NULL )
54 strcpy( stream->filename, filename );
56 if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
60 if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
64 /* Re-add the flags we saved above */
65 stream->status |= status;
69 /* TODO: Setting mbstate */
70 if ( ( stream->handle = _PDCLIB_open( filename, stream->status ) ) == _PDCLIB_NOHANDLE )
80 #include <_PDCLIB_test.h>
86 TESTCASE( ( fin = fopen( testfile1, "wb+" ) ) != NULL );
87 TESTCASE( fputc( 'x', fin ) == 'x' );
88 TESTCASE( fclose( fin ) == 0 );
89 TESTCASE( ( fin = freopen( testfile1, "rb", stdin ) ) != NULL );
90 TESTCASE( getchar() == 'x' );
92 TESTCASE( ( fout = freopen( testfile2, "wb+", stdout ) ) != NULL );
93 TESTCASE( putchar( 'x' ) == 'x' );
95 TESTCASE( fgetc( fout ) == 'x' );
97 TESTCASE( fclose( fin ) == 0 );
98 TESTCASE( fclose( fout ) == 0 );
99 TESTCASE( remove( testfile1 ) == 0 );
100 TESTCASE( remove( testfile2 ) == 0 );