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