fclose · shipping · also fclose(), fclose(3)

fclose

fclose is a C standard-I/O operation that flushes pending output and closes a stream, releasing its underlying file descriptor when one is present.

Related Observatory article: Read on hesela.com

On Linux, check the return: zero indicates success and EOF reports failure with errno set, potentially from writing, flushing or closing. EBADF reports an invalid underlying descriptor. Earlier buffered output can appear successful before fclose reports an error. Neither successful fclose nor successful fflush adds fsync semantics. [1]

After fclose returns, including failure, the FILE pointer must not be used again; retrying fclose on it has undefined behavior. This stream-lifetime rule is distinct from the platform-specific close(2) descriptor rules. Do not confuse a retired stream with an open file descriptor. [1]

POSIX requires unread buffered input to be discarded and an automatically allocated buffer to be freed whether or not the call succeeds. When a writable stream still holds unwritten data, the modification and status-change timestamps are marked for update. [4] FOPEN_MAX, the number of streams guaranteed to be open at once, is at least eight [5] and is 16 in glibc 2.42. [6]

Relations

related
fflush, fwrite, close, fsync, File descriptor

Advantages

  • One call both drains user-space output and releases the descriptor, so a single return value covers the end of a stream. [1]

Limitations

  • Stream closure is not proof of persistent file data.
  • Closing stdin, stdout or stderr can let a later open reuse a standard descriptor number unexpectedly. [4]

Citations

  1. Linux man-pages 6.19: fclose(3), return values and user-space buffers (accessed 2026-10-23)
  2. POSIX.1-2024: fclose() (accessed 2026-10-23)
  3. POSIX.1-2024: stdio.h, FOPEN_MAX (accessed 2026-10-23)
  4. glibc 2.42: libio/stdio.h, BUFSIZ and FOPEN_MAX (accessed 2026-10-23)

Further reading

  1. Linux man-pages 6.19: fflush(3) (accessed 2026-10-21)
  2. Hesela: The user-space buffer comes before fsync (accessed 2026-10-21)
Sources & caveats
  • linux-fclose is the Linux man-pages 6.19 fclose(3) page, re-read for return values, errors and the user-space buffer note.
  • posix-fclose is the POSIX.1-2024 fclose() page, read for buffer disposal, timestamps and standard-stream guidance.
  • posix-stdio is the POSIX.1-2024 stdio.h page, read for the FOPEN_MAX minimum.
  • glibc-stdio is libio/stdio.h at the glibc 2.42 tag, read for the FOPEN_MAX value.
  • The fuse-flush entry links here because closing a stream closes its descriptor, which is when a FUSE filesystem receives FLUSH.

JSON: /data/terms/fclose.json

Published by Hesela team · Updated

Report a correction · Editorial standards · Reuse guidance

Cite this page
Hesela team. fclose. Hesela. 2026-10-23. https://hesela.dev/terms/fclose/