1 #include "stdio_impl.h"
10 FILE *__fdopen(int fd, const char *mode)
15 /* Check for valid initial mode character */
16 if (!strchr("rwa", *mode)) {
21 /* Allocate FILE+buffer or fail */
22 if (!(f=malloc(sizeof *f + UNGET + BUFSIZ))) return 0;
24 /* Zero-fill only the struct, not the buffer */
25 memset(f, 0, sizeof *f);
27 /* Impose mode restrictions */
28 if (!strchr(mode, '+')) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
30 /* Apply close-on-exec flag */
31 if (strchr(mode, 'e')) __syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
33 /* Set append mode on fd if opened for append */
35 int flags = __syscall(SYS_fcntl, fd, F_GETFL);
36 if (!(flags & O_APPEND))
37 __syscall(SYS_fcntl, fd, F_SETFL, flags | O_APPEND);
42 f->buf = (unsigned char *)f + sizeof *f + UNGET;
45 /* Activate line buffered mode for terminals */
47 if (!(f->flags & F_NOWR) && !__syscall(SYS_ioctl, fd, TIOCGWINSZ, &wsz))
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;
56 if (!libc.threaded) f->lock = -1;
58 /* Add new FILE to open file list */
62 weak_alias(__fdopen, fdopen);