fclose.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. libc_hidden_proto(fclose)
  9. libc_hidden_proto(close)
  10. libc_hidden_proto(fflush_unlocked)
  11. int fclose(register FILE *stream)
  12. {
  13. int rv = 0;
  14. __STDIO_AUTO_THREADLOCK_VAR;
  15. /* First, remove the file from the open file list. */
  16. #ifdef __STDIO_HAS_OPENLIST
  17. {
  18. register FILE *ptr;
  19. __STDIO_THREADLOCK_OPENLIST;
  20. if ((ptr = _stdio_openlist) == stream) {
  21. _stdio_openlist = stream->__nextopen;
  22. } else {
  23. while (ptr) {
  24. if (ptr->__nextopen == stream) {
  25. ptr->__nextopen = stream->__nextopen;
  26. break;
  27. }
  28. ptr = ptr->__nextopen;
  29. }
  30. }
  31. __STDIO_THREADUNLOCK_OPENLIST;
  32. if (!ptr) { /* Did not find stream in the open file list! */
  33. return EOF;
  34. }
  35. }
  36. #endif
  37. __STDIO_AUTO_THREADLOCK(stream);
  38. __STDIO_STREAM_VALIDATE(stream);
  39. #ifdef __STDIO_BUFFERS
  40. /* Write any pending buffered chars. */
  41. if (__STDIO_STREAM_IS_WRITING(stream)) {
  42. rv = fflush_unlocked(stream);
  43. }
  44. #endif
  45. if (__CLOSE(stream) < 0) { /* Must close even if fflush failed. */
  46. rv = EOF;
  47. }
  48. stream->__filedes = -1;
  49. /* We need a way for freopen to know that a file has been closed.
  50. * Since a file can't be both readonly and writeonly, that makes
  51. * an effective signal. It also has the benefit of disabling
  52. * transitions to either reading or writing. */
  53. stream->__modeflags &= (__FLAG_FREEBUF|__FLAG_FREEFILE);
  54. stream->__modeflags |= (__FLAG_READONLY|__FLAG_WRITEONLY);
  55. #ifndef NDEBUG
  56. __STDIO_STREAM_RESET_GCS(stream);
  57. /* Reinitialize everything (including putc since fflush could fail). */
  58. __STDIO_STREAM_DISABLE_GETC(stream);
  59. __STDIO_STREAM_DISABLE_PUTC(stream);
  60. __STDIO_STREAM_INIT_BUFREAD_BUFPOS(stream);
  61. # ifdef __UCLIBC_HAS_WCHAR__
  62. stream->__ungot_width[0] = 0;
  63. # endif
  64. # ifdef __STDIO_MBSTATE
  65. __INIT_MBSTATE(&(stream->__state));
  66. # endif
  67. #endif
  68. __STDIO_AUTO_THREADUNLOCK(stream);
  69. __STDIO_STREAM_FREE_BUFFER(stream);
  70. __STDIO_STREAM_FREE_FILE(stream);
  71. return rv;
  72. }
  73. libc_hidden_def(fclose)