add tcgetwinsize and tcsetwinsize functions, move struct winsize
[musl] / src / stdio / __fdopen.c
1 #include "stdio_impl.h"
2 #include <stdlib.h>
3 #include <sys/ioctl.h>
4 #include <termios.h>
5 #include <fcntl.h>
6 #include <errno.h>
7 #include <string.h>
8 #include "libc.h"
9
10 FILE *__fdopen(int fd, const char *mode)
11 {
12         FILE *f;
13         struct winsize wsz;
14
15         /* Check for valid initial mode character */
16         if (!strchr("rwa", *mode)) {
17                 errno = EINVAL;
18                 return 0;
19         }
20
21         /* Allocate FILE+buffer or fail */
22         if (!(f=malloc(sizeof *f + UNGET + BUFSIZ))) return 0;
23
24         /* Zero-fill only the struct, not the buffer */
25         memset(f, 0, sizeof *f);
26
27         /* Impose mode restrictions */
28         if (!strchr(mode, '+')) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
29
30         /* Apply close-on-exec flag */
31         if (strchr(mode, 'e')) __syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
32
33         /* Set append mode on fd if opened for append */
34         if (*mode == 'a') {
35                 int flags = __syscall(SYS_fcntl, fd, F_GETFL);
36                 if (!(flags & O_APPEND))
37                         __syscall(SYS_fcntl, fd, F_SETFL, flags | O_APPEND);
38                 f->flags |= F_APP;
39         }
40
41         f->fd = fd;
42         f->buf = (unsigned char *)f + sizeof *f + UNGET;
43         f->buf_size = BUFSIZ;
44
45         /* Activate line buffered mode for terminals */
46         f->lbf = EOF;
47         if (!(f->flags & F_NOWR) && !__syscall(SYS_ioctl, fd, TIOCGWINSZ, &wsz))
48                 f->lbf = '\n';
49
50         /* Initialize op ptrs. No problem if some are unneeded. */
51         f->read = __stdio_read;
52         f->write = __stdio_write;
53         f->seek = __stdio_seek;
54         f->close = __stdio_close;
55
56         if (!libc.threaded) f->lock = -1;
57
58         /* Add new FILE to open file list */
59         return __ofl_add(f);
60 }
61
62 weak_alias(__fdopen, fdopen);