1 #include "stdio_impl.h"
3 FILE *__fdopen(int fd, const char *mode)
8 /* Check for valid initial mode character */
9 if (!strchr("rwa", *mode)) {
14 /* Allocate FILE+buffer or fail */
15 if (!(f=malloc(sizeof *f + UNGET + BUFSIZ))) return 0;
17 /* Zero-fill only the struct, not the buffer */
18 memset(f, 0, sizeof *f);
20 /* Impose mode restrictions */
21 if (!strchr(mode, '+')) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
23 /* Apply close-on-exec flag */
24 if (strchr(mode, 'e')) __syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
26 /* Set append mode on fd if opened for append */
28 int flags = __syscall(SYS_fcntl, fd, F_GETFL);
29 __syscall(SYS_fcntl, fd, F_SETFL, flags | O_APPEND);
33 f->buf = (unsigned char *)f + sizeof *f + UNGET;
36 /* Activate line buffered mode for terminals */
38 if (!(f->flags & F_NOWR) && !__syscall(SYS_ioctl, fd, TCGETS, &tio))
41 /* Initialize op ptrs. No problem if some are unneeded. */
42 f->read = __stdio_read;
43 f->write = __stdio_write;
44 f->seek = __stdio_seek;
45 f->close = __stdio_close;
47 if (!libc.threaded) f->lock = -1;
49 /* Add new FILE to open file list */
51 f->next = libc.ofl_head;
52 if (libc.ofl_head) libc.ofl_head->prev = f;
59 weak_alias(__fdopen, fdopen);