]> pd.if.org Git - pdclib/blob - functions/stdio/freopen.c
a2c0adade6b91908d5644c7b3dbb1e7ad66fd6b7
[pdclib] / functions / stdio / freopen.c
1 /* $Id$ */
2
3 /* freopen( const char *, const char *, FILE * )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <stdio.h>
10
11 #ifndef REGTEST
12
13 #include <_PDCLIB_glue.h>
14 #include <stdlib.h>
15
16 /* Close any file currently associated with the given stream. Open the file
17    identified by the given filename with the given mode (equivalent to fopen()),
18    and associate it with the given stream. If filename is a NULL pointer,
19    attempt to change the mode of the given stream.
20    This implementation allows any mode changes.
21    (Primary use of this function is to redirect stdin, stdout, and stderr.)
22 */
23 struct _PDCLIB_file_t * freopen( const char * _PDCLIB_restrict filename, const char * _PDCLIB_restrict mode, struct _PDCLIB_file_t * _PDCLIB_restrict stream )
24 {
25     unsigned int status = stream->status & ( _IONBF | _IOLBF | _IOFBF | _PDCLIB_FREEBUFFER | _PDCLIB_DELONCLOSE );
26     /* TODO: This function can change wide orientation of a stream */
27     if ( stream->status & _PDCLIB_FWRITE )
28     {
29         _PDCLIB_flushbuffer( stream );
30     }
31     _PDCLIB_close( stream->handle );
32     clearerr( stream );
33     /* FIXME: Copy filename into the FILE structure. */
34     /* FIXME: filename cannot reside in "big block" memory */
35     if ( filename == NULL )
36     {
37         filename = stream->filename;
38     }
39     if ( ( mode == NULL ) || ( filename[0] == '\0' ) )
40     {
41         return NULL;
42     }
43     if ( ( stream->status = _PDCLIB_filemode( mode ) ) == 0 )
44     {
45         return NULL;
46     }
47     /* Re-add the flags we saved above */
48     stream->status |= status;
49     stream->bufidx = 0;
50     stream->bufend = 0;
51     stream->ungetidx = 0;
52     /* TODO: Setting mbstate */
53     if ( ( stream->handle = _PDCLIB_open( filename, stream->status ) ) == _PDCLIB_NOHANDLE )
54     {
55         return NULL;
56     }
57     return stream;
58 }
59
60 #endif
61
62 #ifdef TEST
63 #include <_PDCLIB_test.h>
64
65 int main( void )
66 {
67     TESTCASE( NO_TESTDRIVER );
68     return TEST_RESULTS;
69 }
70
71 #endif