2 * freopen.c - open a file and associate a stream with it
4 /* $Id: freopen.c,v 1.9 1994/06/24 11:49:53 ceriel Exp $ */
12 /* Do not "optimize" this file to use the open with O_CREAT if the file
13 * does not exist. The reason is given in fopen.c.
21 #define O_APPEND 0x040
23 int _open(const char *path, int flags);
24 int _creat(const char *path, int mode);
28 freopen(const char *name, const char *mode, FILE *stream)
31 int rwmode = 0, rwflags = 0;
32 int fd, flags = stream->_flags & (_IONBF | _IOFBF | _IOLBF | _IOMYBUF);
34 (void) fflush(stream); /* ignore errors */
35 (void) _close(fileno(stream));
45 rwflags = O_CREAT | O_TRUNC;
48 flags |= _IOWRITE | _IOAPPEND;
50 rwflags |= O_APPEND | O_CREAT;
62 flags |= _IOREAD | _IOWRITE;
64 /* The sequence may be followed by aditional characters */
71 if ((rwflags & O_TRUNC)
72 || (((fd = _open(name, rwmode)) < 0)
73 && (rwflags & O_CREAT))) {
74 if (((fd = _creat(name, PMODE)) < 0) && flags | _IOREAD) {
76 fd = _open(name, rwmode);
81 for( i = 0; i < FOPEN_MAX; i++) {
82 if (stream == __iotab[i]) {
87 if (stream != stdin && stream != stdout && stream != stderr)
94 stream->_flags = flags;