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.
12 #include <_PDCLIB_io.h>
13 #include <_PDCLIB_glue.h>
18 const char * _PDCLIB_restrict filename,
19 const char * _PDCLIB_restrict mode,
20 FILE * _PDCLIB_restrict stream
25 unsigned int status = stream->status &
26 ( _IONBF | _IOLBF | _IOFBF | _PDCLIB_FREEBUFFER
27 | _PDCLIB_DELONCLOSE | _PDCLIB_STATIC );
29 /* TODO: This function can change wide orientation of a stream */
30 if ( stream->status & _PDCLIB_FWRITE )
32 _PDCLIB_flushbuffer( stream );
34 if ( ( filename == NULL ) && ( stream->filename == NULL ) )
36 /* TODO: Special handling for mode changes on std-streams */
37 funlockfile( stream );
40 stream->ops->close(stream->handle);
42 /* TODO: It is not nice to do this on a stream we just closed.
43 It does not matter with the current implementation of clearerr(),
44 but it might start to matter if someone replaced that implementation.
47 /* The new filename might not fit the old buffer */
48 if ( filename == NULL )
50 /* Use previous filename */
51 filename = stream->filename;
53 else if ( ( stream->filename != NULL ) && ( strlen( stream->filename ) >= strlen( filename ) ) )
55 /* Copy new filename into existing buffer */
56 strcpy( stream->filename, filename );
60 /* Allocate new buffer */
61 if ( ( stream->filename = (char *)malloc( strlen( filename ) ) ) == NULL )
63 funlockfile( stream );
66 strcpy( stream->filename, filename );
68 if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
70 funlockfile( stream );
73 if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
75 funlockfile( stream );
78 /* Re-add the flags we saved above */
79 stream->status |= status;
83 /* TODO: Setting mbstate */
84 if ( ! _PDCLIB_open( &stream->handle, &stream->ops, filename,
87 funlockfile( stream );
90 funlockfile( stream );
97 #include <_PDCLIB_test.h>
103 TESTCASE( ( fin = fopen( testfile1, "wb+" ) ) != NULL );
104 TESTCASE( fputc( 'x', fin ) == 'x' );
105 TESTCASE( fclose( fin ) == 0 );
106 TESTCASE( ( fin = freopen( testfile1, "rb", stdin ) ) != NULL );
107 TESTCASE( getchar() == 'x' );
109 TESTCASE( ( fout = freopen( testfile2, "wb+", stdout ) ) != NULL );
110 TESTCASE( putchar( 'x' ) == 'x' );
112 TESTCASE( fgetc( fout ) == 'x' );
114 TESTCASE( fclose( fin ) == 0 );
115 TESTCASE( fclose( fout ) == 0 );
116 TESTCASE( remove( testfile1 ) == 0 );
117 TESTCASE( remove( testfile2 ) == 0 );