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