1
0

__fdopen.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. FILE *__fdopen(int fd, const char *mode)
  9. {
  10. FILE *f;
  11. struct termios tio;
  12. /* Check for valid initial mode character */
  13. if (!strchr("rwa", *mode)) {
  14. errno = EINVAL;
  15. return 0;
  16. }
  17. /* Allocate FILE+buffer or fail */
  18. if (!(f=malloc(sizeof *f + UNGET + BUFSIZ))) return 0;
  19. /* Zero-fill only the struct, not the buffer */
  20. memset(f, 0, sizeof *f);
  21. /* Impose mode restrictions */
  22. 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);
  25. /* Set append mode on fd if opened for append */
  26. if (*mode == 'a') {
  27. int flags = __syscall(SYS_fcntl, fd, F_GETFL);
  28. __syscall(SYS_fcntl, fd, F_SETFL, flags | O_APPEND);
  29. }
  30. f->fd = fd;
  31. f->buf = (unsigned char *)f + sizeof *f + UNGET;
  32. f->buf_size = BUFSIZ;
  33. /* Activate line buffered mode for terminals */
  34. f->lbf = EOF;
  35. if (!(f->flags & F_NOWR) && !__syscall(SYS_ioctl, fd, TCGETS, &tio))
  36. f->lbf = '\n';
  37. /* Initialize op ptrs. No problem if some are unneeded. */
  38. f->read = __stdio_read;
  39. f->write = __stdio_write;
  40. f->seek = __stdio_seek;
  41. f->close = __stdio_close;
  42. if (!libc.threaded) f->lock = -1;
  43. /* Add new FILE to open file list */
  44. OFLLOCK();
  45. f->next = libc.ofl_head;
  46. if (libc.ofl_head) libc.ofl_head->prev = f;
  47. libc.ofl_head = f;
  48. OFLUNLOCK();
  49. return f;
  50. }
  51. weak_alias(__fdopen, fdopen);