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 stream->ops->close(stream->handle);
38 /* TODO: It is not nice to do this on a stream we just closed.
39 It does not matter with the current implementation of clearerr(),
40 but it might start to matter if someone replaced that implementation.
43 /* The new filename might not fit the old buffer */
44 if ( filename == NULL )
46 /* Use previous filename */
47 filename = stream->filename;
49 else if ( ( stream->filename != NULL ) && ( strlen( stream->filename ) >= strlen( filename ) ) )
51 /* Copy new filename into existing buffer */
52 strcpy( stream->filename, filename );
56 /* Allocate new buffer */
57 if ( ( stream->filename = (char *)malloc( strlen( filename ) ) ) == NULL )
59 funlockfile( stream );
62 strcpy( stream->filename, filename );
64 if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
66 funlockfile( stream );
69 if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
71 funlockfile( stream );
74 /* Re-add the flags we saved above */
75 stream->status |= status;
79 /* TODO: Setting mbstate */
80 if ( ! _PDCLIB_open( &stream->handle, &stream->ops, filename,
83 funlockfile( stream );
86 funlockfile( stream );
93 #include <_PDCLIB_test.h>
99 TESTCASE( ( fin = fopen( testfile1, "wb+" ) ) != NULL );
100 TESTCASE( fputc( 'x', fin ) == 'x' );
101 TESTCASE( fclose( fin ) == 0 );
102 TESTCASE( ( fin = freopen( testfile1, "rb", stdin ) ) != NULL );
103 TESTCASE( getchar() == 'x' );
105 TESTCASE( ( fout = freopen( testfile2, "wb+", stdout ) ) != NULL );
106 TESTCASE( putchar( 'x' ) == 'x' );
108 TESTCASE( fgetc( fout ) == 'x' );
110 TESTCASE( fclose( fin ) == 0 );
111 TESTCASE( fclose( fout ) == 0 );
112 TESTCASE( remove( testfile1 ) == 0 );
113 TESTCASE( remove( testfile2 ) == 0 );