fclose() Close a file stream
fclose() Close a file stream
fclose() flushes and closes a stream, returning 0 on success or EOF on error. Check delayed write failures; never reuse or close the pointer again.
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
int fclose(FILE *stream);
⚙️ Parameters
| stream Required | A valid stream previously returned by fopen(), freopen(), tmpfile(), or a similar function. |
|---|
Returns: Returns zero on success, or EOF if an error occurs.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Stream closed successfully
⚠️ Warning Do not use the original stream pointer after closing it, and do not close the same stream twice; either action causes undefined behavior.
💡 Tip Checking fclose() is important for output files because buffered write errors can first become visible during close.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QWhy should I check the return value of fclose?
AClosing flushes remaining buffered data to the underlying device, which can still fail because of a full disk or device error. Ignoring it can hide data loss.
QCan I use the original FILE pointer after fclose?
ANo. The stream object's lifetime has ended, so further I/O or another close is invalid. Reopen the file if it must be accessed again.
QCan I omit fclose before a program exits normally?
AA normal exit() or return from main flushes and closes open streams, but that is no substitute for explicit closes: long-running programs can accumulate stream resources, and per-stream close errors are difficult to handle during exit. For important output, call fclose() and check its result to catch delayed write failures.