Nearby lessons
69 of 72C - 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
Loading editor…
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
Loading editor…
📝 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 QuestionsProgress: 0 / 3
Finished this lesson?
Mark it as complete to track your progress and see technology completion stats.