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

Checking for NULL file pointers

Checking for NULL file pointers

What you'll learn: How to verify that a file successfully opened before your program tries to read or write to it.

The "Missing Key" problem

Imagine you arrive at a locked storage unit. You reach into your pocket for the key, but your hand comes up empty. If you try to turn a non-existent key in the lock, nothing happens—or worse, you might hurt yourself trying to force it.

In C, when you use the fopen() function, the operating system tries to find the file and give you a "key" (a pointer to a FILE structure). If the file doesn't exist, if it’s locked by another program, or if you don't have permission to see it, the operating system can't give you that key. Instead, it gives you NULL—a special value that represents "nothing."

Why checking is mandatory

If you ignore the possibility of a NULL pointer and immediately try to read from it, your program will crash instantly. This is called "dereferencing a null pointer." It is one of the most common causes of software failure. Since C doesn't automatically stop you from making this mistake, you must build a "safety gate" into your code.

How to build the safety gate

Immediately after calling fopen(), you should use an if statement to check if your file pointer is equal to NULL. If it is, you should print an error message and stop the operation.

#include <stdio.h>

int main() {
    // Attempt to open a file for reading
    FILE *fptr = fopen("my_secret_data.txt", "r");

    // The Safety Gate: Check if the file pointer is NULL
    if (fptr == NULL) {
        printf("Error: Could not open the file. It might be missing!\n");
        return 1; // Exit the program with an error code
    }

    // If we reach this point, it is safe to work with the file
    printf("File opened successfully. Ready to read data.\n");

    fclose(fptr);
    return 0;
}

When does this happen?

You might think your files are always there, but NULL pointers happen often in the real world. A user might rename a folder, a USB drive might be unplugged, or you might simply have a typo in the filename. By checking for NULL, you turn a potential crash into a helpful message.

Key takeaway

Always check if your file pointer is NULL immediately after fopen() to prevent your program from crashing.