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

Closing files with fclose

Closing files with fclose

What you'll learn: How to properly disconnect your program from a file to ensure data is saved and system resources are freed.

The "Open Door" Problem

Imagine you are a librarian. When a patron wants to read a book, you take it off the shelf and open it on a table. This takes up space in the library (memory) and prevents other people from putting that book back in its permanent spot. If you keep opening books and never shutting them, eventually your tables are full, the library is a mess, and some books might even get damaged or lost in the clutter.

In C, when you use fopen(), you are opening a "stream." Your computer sets aside a small chunk of memory to manage that connection. If you finish your work but forget to tell the computer you’re done, that memory stays occupied. Even worse, C often uses a "buffer"—a temporary waiting room for data. If you write text to a file but don't close it, that text might still be sitting in the buffer waiting to be sent, and it could vanish if the program ends abruptly.

Using fclose()

To safely tuck your data away and tidy up, you use the fclose() function. It takes one argument: the file pointer you created when you opened the file.

When you call fclose(), C performs two vital tasks:

  1. Flushing: It forces any leftover data in the buffer to be physically written to the disk.
  2. Releasing: It tells the operating system that the file is no longer in use, freeing up system resources.
#include <stdio.h>

int main() {
    // 1. Open the file
    FILE *myFile = fopen("notes.txt", "w");

    if (myFile != NULL) {
        // 2. Perform your work
        fprintf(myFile, "Saving this for later!");

        // 3. Close the file (The most important step!)
        fclose(myFile);
    }

    return 0;
}

Why it matters

In a tiny program, forgetting to close a file might not cause an immediate crash because the operating system usually cleans up after a program ends. However, in professional software that runs for days or weeks, "leaking" file connections will eventually cause the program to run out of memory or reach the limit of how many files it is allowed to have open at once.

Think of fclose() as the "Save and Exit" button. You wouldn't walk away from a document you spent hours writing without hitting save; don't finish your C code without closing your files.

Key takeaway

Always pair every fopen() with an fclose() to prevent data loss and resource leaks.