__fdopen.c 1.4 KB

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