1 /* freopen( const char *, const char *, FILE * )
3 This file is part of the Public Domain C Library (PDCLib).
4 Permission is granted to use, modify, and / or redistribute at will.
13 #include "_PDCLIB_glue.h"
15 struct _PDCLIB_file_t * freopen( const char * _PDCLIB_restrict filename, const char * _PDCLIB_restrict mode, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
17 unsigned int status = stream->status & ( _IONBF | _IOLBF | _IOFBF | _PDCLIB_FREEBUFFER | _PDCLIB_DELONCLOSE );
18 /* TODO: This function can change wide orientation of a stream */
19 if ( stream->status & _PDCLIB_FWRITE )
21 _PDCLIB_flushbuffer( stream );
23 if ( ( filename == NULL ) && ( stream->filename == NULL ) )
25 /* TODO: Special handling for mode changes on std-streams */
28 _PDCLIB_close( stream->handle );
29 /* TODO: It is not nice to do this on a stream we just closed.
30 It does not matter with the current implementation of clearerr(),
31 but it might start to matter if someone replaced that implementation.
34 /* The new filename might not fit the old buffer */
35 if ( filename == NULL )
37 /* Use previous filename */
38 filename = stream->filename;
40 else if ( ( stream->filename != NULL ) && ( strlen( stream->filename ) >= strlen( filename ) ) )
42 /* Copy new filename into existing buffer */
43 strcpy( stream->filename, filename );
47 /* Allocate new buffer */
48 if ( ( stream->filename = (char *)malloc( strlen( filename ) ) ) == NULL )
52 strcpy( stream->filename, filename );
54 if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
58 if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
62 /* Re-add the flags we saved above */
63 stream->status |= status;
67 /* TODO: Setting mbstate */
68 if ( ( stream->handle = _PDCLIB_open( filename, stream->status ) ) == _PDCLIB_NOHANDLE )
79 #include "_PDCLIB_test.h"
85 TESTCASE( ( fin = fopen( testfile1, "wb+" ) ) != NULL );
86 TESTCASE( fputc( 'x', fin ) == 'x' );
87 TESTCASE( fclose( fin ) == 0 );
88 TESTCASE( ( fin = freopen( testfile1, "rb", stdin ) ) != NULL );
89 TESTCASE( getchar() == 'x' );
91 TESTCASE( ( fout = freopen( testfile2, "wb+", stdout ) ) != NULL );
92 TESTCASE( putchar( 'x' ) == 'x' );
94 TESTCASE( fgetc( fout ) == 'x' );
96 TESTCASE( fclose( fin ) == 0 );
97 TESTCASE( fclose( fout ) == 0 );
98 TESTCASE( remove( testfile1 ) == 0 );
99 TESTCASE( remove( testfile2 ) == 0 );