freopen.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* Copyright (C) 2004 Manuel Novoa III <mjn3@codepoet.org>
  2. *
  3. * GNU Library General Public License (LGPL) version 2 or later.
  4. *
  5. * Dedicated to Toni. See uClibc/DEDICATION.mjn3 for details.
  6. */
  7. #include "_stdio.h"
  8. #ifndef __DO_LARGEFILE
  9. # define FILEDES_ARG (-1)
  10. #endif
  11. FILE *freopen(const char * __restrict filename, const char * __restrict mode,
  12. register FILE * __restrict stream)
  13. {
  14. /*
  15. * ANSI/ISO allow (implementation-defined) change of mode for an
  16. * existing file if filename is NULL. It doesn't look like Linux
  17. * supports this, so we don't here.
  18. *
  19. * NOTE: Whether or not the stream is free'd on failure is unclear
  20. * w.r.t. ANSI/ISO. This implementation chooses to NOT free
  21. * the stream and associated buffer if they were dynamically
  22. * allocated.
  23. * NOTE: Previous versions of uClibc did free dynamic storage.
  24. *
  25. * TODO: Apparently linux allows setting append mode. Implement?
  26. */
  27. unsigned short dynmode;
  28. register FILE *fp;
  29. __STDIO_AUTO_THREADLOCK_VAR;
  30. __STDIO_AUTO_THREADLOCK(stream);
  31. __STDIO_STREAM_VALIDATE(stream);
  32. /* First, flush and close, but don't deallocate, the stream. */
  33. /* This also removes the stream for the open file list. */
  34. dynmode = (stream->__modeflags & (__FLAG_FREEBUF|__FLAG_FREEFILE));
  35. stream->__modeflags &= ~(__FLAG_FREEBUF|__FLAG_FREEFILE);
  36. /* Only call fclose on the stream if it is not already closed. */
  37. if ((stream->__modeflags & (__FLAG_READONLY|__FLAG_WRITEONLY))
  38. != (__FLAG_READONLY|__FLAG_WRITEONLY)
  39. ) {
  40. fclose(stream); /* Failures are ignored. */
  41. }
  42. fp = _stdio_fopen(((intptr_t) filename), mode, stream, FILEDES_ARG);
  43. /* Reset the allocation flags. */
  44. stream->__modeflags |= dynmode;
  45. __STDIO_AUTO_THREADUNLOCK(stream);
  46. return fp;
  47. }