How to Use fclose in C: Syntax, Example, and Tips
In C, use
fclose(FILE *stream) to close an open file and free its resources. It takes a file pointer returned by fopen and returns 0 on success or EOF on failure.Syntax
The fclose function closes a file opened by fopen. It takes one argument:
FILE *stream: The pointer to the file to close.
It returns 0 if the file closes successfully, or EOF if there is an error.
c
int fclose(FILE *stream);Example
This example opens a file for writing, writes a line, then closes the file using fclose. It checks if closing was successful.
c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "w"); if (file == NULL) { printf("Failed to open file.\n"); return 1; } fprintf(file, "Hello, fclose!\n"); if (fclose(file) == 0) { printf("File closed successfully.\n"); } else { printf("Error closing file.\n"); } return 0; }
Output
File closed successfully.
Common Pitfalls
Common mistakes when using fclose include:
- Not checking if the file was opened successfully before calling
fclose. - Calling
fcloseon aNULLpointer, which causes undefined behavior. - Forgetting to close files, which can cause resource leaks.
- Ignoring the return value of
fclose, missing errors like write failures.
c
#include <stdio.h> int main() { FILE *file = NULL; // Wrong: fclose on NULL pointer // fclose(file); // This causes undefined behavior file = fopen("test.txt", "r"); if (file != NULL) { // Correct: fclose only if file opened if (fclose(file) == 0) { printf("File closed properly.\n"); } else { printf("Error closing file.\n"); } } return 0; }
Output
File closed properly.
Quick Reference
- fclose(FILE *stream): Closes the file and frees resources.
- Returns
0on success,EOFon error. - Always check if
fopensucceeded before callingfclose. - Close every file you open to avoid resource leaks.
Key Takeaways
Always close files with fclose to free system resources.
Check that fopen succeeded before calling fclose.
fclose returns 0 on success and EOF on failure; always check it.
Never call fclose on a NULL or already closed file pointer.
Forgetting fclose can cause file corruption or resource leaks.