1 #include "stdio_impl.h"
8 FILE *__fdopen(int fd, const char *mode)
13 /* Check for valid initial mode character */
14 if (!strchr("rwa", *mode)) {
19 /* Allocate FILE+buffer or fail */
20 if (!(f=malloc(sizeof *f + UNGET + BUFSIZ))) return 0;
22 /* Zero-fill only the struct, not the buffer */
23 memset(f, 0, sizeof *f);
25 /* Impose mode restrictions */
26 if (!strchr(mode, '+')) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
28 /* Apply close-on-exec flag */
29 if (strchr(mode, 'e')) __syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
31 /* Set append mode on fd if opened for append */
33 int flags = __syscall(SYS_fcntl, fd, F_GETFL);
34 if (!(flags & O_APPEND))
35 __syscall(SYS_fcntl, fd, F_SETFL, flags | O_APPEND);
40 f->buf = (unsigned char *)f + sizeof *f + UNGET;
43 /* Activate line buffered mode for terminals */
45 if (!(f->flags & F_NOWR) && !__syscall(SYS_ioctl, fd, TIOCGWINSZ, &wsz))
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;
54 if (!libc.threaded) f->lock = -1;
56 /* Add new FILE to open file list */
58 f->next = libc.ofl_head;
59 if (libc.ofl_head) libc.ofl_head->prev = f;
66 weak_alias(__fdopen, fdopen);