Course contentsShow
← C
Lesson 747 of 1,21910. Input and OutputFree lesson

Safe file closing patterns

Safe file closing patterns

What you'll learn: How to properly close files in C to prevent memory leaks and ensure your data is actually saved to the disk.

Why closing matters

Imagine you are writing in a physical notebook. When you finish, you don't just leave it open on the table; you close the cover to protect the pages. In C, closing a file with fclose() does two vital things: it releases the memory the operating system allocated to handle that file, and it "flushes" the data.

Computers often hold data in a temporary waiting area (a buffer) rather than writing to the slow hard drive instantly. If your program crashes or finishes without closing the file, that data might stay in the buffer forever, leaving you with an empty or corrupted file.

The "Null and Check" pattern

A common mistake is trying to close a file that never opened successfully. If fopen() fails, it returns NULL. If you pass NULL to fclose(), your program will likely crash.

The safest way to handle this is to check if the file pointer is valid before closing it, and then set the pointer to NULL immediately after closing. Setting the pointer to NULL is like shredding a key after you’ve locked a door—it prevents you from accidentally trying to use that "key" again later in your code, which would cause a "double-free" error.

A safe closing example

Here is how you handle a file lifecycle safely:

#include <stdio.h>

int main() {
    FILE *fptr = fopen("notes.txt", "w");

    // 1. Check if the file opened successfully
    if (fptr != NULL) {
        fprintf(fptr, "Saving important data...");

        // 2. Close the file and check if it succeeded
        if (fclose(fptr) == 0) {
            printf("File closed successfully.\n");
        } else {
            printf("Error: Data might not have saved correctly.\n");
        }

        // 3. Set to NULL to prevent accidental reuse
        fptr = NULL;
    }

    return 0;
}

Defensive programming

In larger programs, you might have hundreds of lines of code between opening and closing a file. By always checking if (fptr != NULL) before calling fclose(), you build a safety net. This practice ensures that even if an error occurs earlier in your logic, your cleanup code won't make a bad situation worse by triggering a crash.

Key takeaway

Always check that a file pointer isn't NULL before closing it, and set the pointer to NULL afterward to stay safe.