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 &
25 ( _IONBF | _IOLBF | _IOFBF | _PDCLIB_FREEBUFFER
26 | _PDCLIB_DELONCLOSE | _PDCLIB_STATIC );
28 /* TODO: This function can change wide orientation of a stream */
29 if ( stream->status & _PDCLIB_FWRITE )
31 _PDCLIB_flushbuffer( stream );
33 if ( ( filename == NULL ) && ( stream->filename == NULL ) )
35 /* TODO: Special handling for mode changes on std-streams */
36 funlockfile( stream );
39 stream->ops->close(stream->handle);
41 /* TODO: It is not nice to do this on a stream we just closed.
42 It does not matter with the current implementation of clearerr(),
43 but it might start to matter if someone replaced that implementation.
46 /* The new filename might not fit the old buffer */
47 if ( filename == NULL )
49 /* Use previous filename */
50 filename = stream->filename;
52 else if ( ( stream->filename != NULL ) && ( strlen( stream->filename ) >= strlen( filename ) ) )
54 /* Copy new filename into existing buffer */
55 strcpy( stream->filename, filename );
59 /* Allocate new buffer */
60 if ( ( stream->filename = (char *)malloc( strlen( filename ) ) ) == NULL )
62 funlockfile( stream );
65 strcpy( stream->filename, filename );
67 if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
69 funlockfile( stream );
72 if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
74 funlockfile( stream );
77 /* Re-add the flags we saved above */
78 stream->status |= status;
82 /* TODO: Setting mbstate */
83 if ( ! _PDCLIB_open( &stream->handle, &stream->ops, filename,
86 funlockfile( stream );
89 funlockfile( stream );
96 #include <_PDCLIB_test.h>
102 TESTCASE( ( fin = fopen( testfile1, "wb+" ) ) != NULL );
103 TESTCASE( fputc( 'x', fin ) == 'x' );
104 TESTCASE( fclose( fin ) == 0 );
105 TESTCASE( ( fin = freopen( testfile1, "rb", stdin ) ) != NULL );
106 TESTCASE( getchar() == 'x' );
108 TESTCASE( ( fout = freopen( testfile2, "wb+", stdout ) ) != NULL );
109 TESTCASE( putchar( 'x' ) == 'x' );
111 TESTCASE( fgetc( fout ) == 'x' );
113 TESTCASE( fclose( fin ) == 0 );
114 TESTCASE( fclose( fout ) == 0 );
115 TESTCASE( remove( testfile1 ) == 0 );
116 TESTCASE( remove( testfile2 ) == 0 );