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.
10 #include <_PDCLIB_io.h>
11 #include <_PDCLIB_glue.h>
16 const char * _PDCLIB_restrict filename,
17 const char * _PDCLIB_restrict mode,
18 FILE * _PDCLIB_restrict stream
21 _PDCLIB_flockfile( stream );
23 unsigned int status = stream->status &
24 ( _IONBF | _IOLBF | _IOFBF | _PDCLIB_FREEBUFFER
25 | _PDCLIB_DELONCLOSE | _PDCLIB_STATIC );
27 /* TODO: This function can change wide orientation of a stream */
28 if ( stream->status & _PDCLIB_FWRITE )
30 _PDCLIB_flushbuffer( stream );
32 if ( ( filename == NULL ) && ( stream->filename == NULL ) )
34 /* TODO: Special handling for mode changes on std-streams */
35 _PDCLIB_funlockfile( stream );
38 stream->ops->close(stream->handle);
40 /* TODO: It is not nice to do this on a stream we just closed.
41 It does not matter with the current implementation of clearerr(),
42 but it might start to matter if someone replaced that implementation.
44 _PDCLIB_clearerr_unlocked( stream );
45 /* The new filename might not fit the old buffer */
46 if ( filename == NULL )
48 /* Use previous filename */
49 filename = stream->filename;
51 else if ( ( stream->filename != NULL ) && ( strlen( stream->filename ) >= strlen( filename ) ) )
53 /* Copy new filename into existing buffer */
54 strcpy( stream->filename, filename );
58 /* Allocate new buffer */
59 if ( ( stream->filename = (char *)malloc( strlen( filename ) ) ) == NULL )
61 _PDCLIB_funlockfile( stream );
64 strcpy( stream->filename, filename );
66 if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
68 _PDCLIB_funlockfile( stream );
71 if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
73 _PDCLIB_funlockfile( stream );
76 /* Re-add the flags we saved above */
77 stream->status |= status;
81 /* TODO: Setting mbstate */
82 if ( ! _PDCLIB_open( &stream->handle, &stream->ops, filename,
85 _PDCLIB_funlockfile( stream );
88 _PDCLIB_funlockfile( stream );
95 #include <_PDCLIB_test.h>
101 TESTCASE( ( fin = fopen( testfile1, "wb+" ) ) != NULL );
102 TESTCASE( fputc( 'x', fin ) == 'x' );
103 TESTCASE( fclose( fin ) == 0 );
104 TESTCASE( ( fin = freopen( testfile1, "rb", stdin ) ) != NULL );
105 TESTCASE( getchar() == 'x' );
107 TESTCASE( ( fout = freopen( testfile2, "wb+", stdout ) ) != NULL );
108 TESTCASE( putchar( 'x' ) == 'x' );
110 TESTCASE( fgetc( fout ) == 'x' );
112 TESTCASE( fclose( fin ) == 0 );
113 TESTCASE( fclose( fout ) == 0 );
114 TESTCASE( remove( testfile1 ) == 0 );
115 TESTCASE( remove( testfile2 ) == 0 );