2 * freopen.c - open a file and associate a stream with it
6 #if defined(_POSIX_SOURCE)
16 /* Do not "optimize" this file to use the open with O_CREAT if the file
17 * does not exist. The reason is given in fopen.c.
25 #define O_APPEND 0x040
27 int _open(const char *path
, int flags
);
28 int _creat(const char *path
, _mnx_Mode_t mode
);
32 freopen(const char *name
, const char *mode
, FILE *stream
)
36 int rwmode
= 0, rwflags
= 0;
37 int fd
, flags
= stream
->_flags
& (_IONBF
| _IOFBF
| _IOLBF
| _IOMYBUF
);
39 (void) fflush(stream
); /* ignore errors */
40 (void) _close(fileno(stream
));
50 rwflags
= O_CREAT
| O_TRUNC
;
53 flags
|= _IOWRITE
| _IOAPPEND
;
55 rwflags
|= O_APPEND
| O_CREAT
;
67 flags
|= _IOREAD
| _IOWRITE
;
69 /* The sequence may be followed by aditional characters */
76 if ((rwflags
& O_TRUNC
)
77 || (((fd
= _open(name
, rwmode
)) < 0)
78 && (rwflags
& O_CREAT
))) {
79 if (((fd
= _creat(name
, PMODE
)) < 0) && flags
| _IOREAD
) {
81 fd
= _open(name
, rwmode
);
89 if ( fstat( fd
, &st
) == 0 ) {
90 if ( S_ISFIFO(st
.st_mode
) ) flags
|= _IOFIFO
;
97 stream
->_flags
= flags
;
101 for( i
= 0; i
< FOPEN_MAX
; i
++) {
102 if (stream
== __iotab
[i
]) {
107 if (stream
!= stdin
&& stream
!= stdout
&& stream
!= stderr
)
108 free((void *)stream
);