Nearby lessons

69 of 72

C - Close a File

The fclose() function closes a file that was opened with fopen(). Closing a file helps finish pending output and releases the resources used to access it.

1. Syntax of fclose()

The fclose() function takes the file pointer as its argument.

fclose(fp);

Example01
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("data.txt", "w");
5 
6 if (fp == NULL) {
7 printf("Could not open the file\n");
8 return 1;
9 }
10 
11 fprintf(fp, "File handling in C\n");
12 
13 if (fclose(fp) == 0) {
14 printf("File closed successfully\n");
15 } else {
16 printf("An error occurred while closing the file\n");
17 return 1;
18 }
19 
20 return 0;
21}
Output
File closed successfully

2. Why Should We Close a File?

  • It completes pending file output.
  • It releases resources associated with the opened file.
  • It helps avoid keeping too many files open.

Make sure each successful fopen() is matched with a call to fclose().

3. Do Not Use a Closed File Pointer

After calling fclose(fp), do not use fp for file operations again. If the pointer variable will remain in use, assigning NULL can help make its closed state clear.

Example03
CCode Cell
1FILE *fp = fopen("data.txt", "w");
2 
3if (fp == NULL) {
4 return 1;
5}
6 
7fprintf(fp, "Hello\n");
8fclose(fp);
9fp = NULL;
10 
11/* Do not call fprintf(fp, ...) after closing the file. */
📝 Key Takeaways
  • Use fclose(fp) when you finish working with an opened file.
  • fclose() returns 0 on success and EOF if an error occurs.
  • Check fopen() for NULL before using the file.
  • Do not read or write through a file pointer after closing it.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3