How to Close a File in C: Syntax and Examples
In C, you close a file using the
fclose() function by passing the file pointer returned by fopen(). This releases the file resource and ensures all data is saved properly.Syntax
The syntax to close a file in C is simple. You use the fclose() function and pass it the file pointer you got when opening the file.
FILE *filePointer;- This is the variable holding the file reference.fclose(filePointer);- This closes the file and frees resources.
c
int fclose(FILE *stream);Example
This example shows how to open a file, write some text, and then close it properly using fclose(). Closing the file ensures all data is saved and resources are freed.
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, file!\n"); if (fclose(file) == 0) { printf("File closed successfully.\n"); } else { printf("Error closing file.\n"); } return 0; }
Output
File closed successfully.
Common Pitfalls
Some common mistakes when closing files in C include:
- Not checking if the file was opened successfully before closing.
- Forgetting to close the file, which can cause data loss or resource leaks.
- Using
fclose()on aNULLor invalid file pointer.
Always check the return value of fclose() to confirm the file closed properly.
c
#include <stdio.h> int main() { FILE *file = NULL; // Wrong: fclose called on NULL pointer // fclose(file); // This causes undefined behavior // Right way: file = fopen("example.txt", "r"); if (file != NULL) { fclose(file); printf("File closed safely.\n"); } else { printf("File not opened, so not closed.\n"); } return 0; }
Output
File not opened, so not closed.
Quick Reference
Remember these tips when closing files in C:
- Use
fclose(filePointer);to close files. - Check if the file pointer is not
NULLbefore closing. - Check the return value of
fclose()for success (returns 0) or failure (EOF). - Always close files to avoid memory leaks and data loss.
Key Takeaways
Always close files in C using fclose() to free resources and save data.
Check that the file pointer is valid before calling fclose().
Check fclose() return value to confirm the file closed successfully.
Not closing files can cause data loss or resource leaks.
Use fopen() and fclose() together to manage file access safely.