1
0

freopen.c 994 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include "stdio_impl.h"
  2. /* The basic idea of this implementation is to open a new FILE,
  3. * hack the necessary parts of the new FILE into the old one, then
  4. * close the new FILE. */
  5. /* Locking is not necessary because, in the event of failure, the stream
  6. * passed to freopen is invalid as soon as freopen is called. */
  7. FILE *freopen(const char *filename, const char *mode, FILE *f)
  8. {
  9. int fl;
  10. FILE *f2;
  11. fflush(f);
  12. if (!filename) {
  13. f2 = fopen("/dev/null", mode);
  14. if (!f2) goto fail;
  15. fl = syscall(SYS_fcntl, f2->fd, F_GETFL, 0);
  16. if (fl < 0 || syscall(SYS_fcntl, f->fd, F_SETFL, fl) < 0)
  17. goto fail2;
  18. } else {
  19. f2 = fopen(filename, mode);
  20. if (!f2) goto fail;
  21. if (syscall(SYS_dup2, f2->fd, f->fd) < 0)
  22. goto fail2;
  23. }
  24. f->flags = (f->flags & F_PERM) | f2->flags;
  25. f->read = f2->read;
  26. f->write = f2->write;
  27. f->seek = f2->seek;
  28. f->close = f2->close;
  29. f->flush = f2->flush;
  30. fclose(f2);
  31. return f;
  32. fail2:
  33. fclose(f2);
  34. fail:
  35. fclose(f);
  36. return NULL;
  37. }
  38. LFS64(freopen);