c80ce3b438e67e7de275cd2ef1a3a0513d5e05cd
[musl] / src / stdio / freopen.c
1 #include "stdio_impl.h"
2
3 /* The basic idea of this implementation is to open a new FILE,
4  * hack the necessary parts of the new FILE into the old one, then
5  * close the new FILE. */
6
7 /* Locking is not necessary because, in the event of failure, the stream
8  * passed to freopen is invalid as soon as freopen is called. */
9
10 int __dup3(int, int, int);
11
12 FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict f)
13 {
14         int fl = __fmodeflags(mode);
15         FILE *f2;
16
17         fflush(f);
18
19         if (!filename) {
20                 if (fl&O_CLOEXEC)
21                         __syscall(SYS_fcntl, f->fd, F_SETFD, FD_CLOEXEC);
22                 fl &= ~(O_CREAT|O_EXCL|O_CLOEXEC);
23                 if (syscall(SYS_fcntl, f->fd, F_SETFL, fl) < 0)
24                         goto fail;
25                 return f;
26         } else {
27                 f2 = fopen(filename, mode);
28                 if (!f2) goto fail;
29                 if (f2->fd == f->fd) f2->fd = -1; /* avoid closing in fclose */
30                 else if (__dup3(f2->fd, f->fd, fl&O_CLOEXEC)<0) goto fail2;
31         }
32
33         f->flags = (f->flags & F_PERM) | f2->flags;
34         f->read = f2->read;
35         f->write = f2->write;
36         f->seek = f2->seek;
37         f->close = f2->close;
38
39         fclose(f2);
40         return f;
41
42 fail2:
43         fclose(f2);
44 fail:
45         fclose(f);
46         return NULL;
47 }
48
49 LFS64(freopen);