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

Checking for NULL return in fgets

Checking for NULL return in fgets

What you'll learn: How to determine if a file has reached its end or encountered an error by checking the return value of fgets.

The Safety Guard

When you use fgets to read a line of text, you are essentially asking C to reach into a file and grab a handful of characters. But what happens if the hand comes back empty? If you are at the very end of a file (EOF) or if a hardware error occurs, there is no data to put into your string buffer.

Instead of crashing or leaving you guessing, fgets communicates this to you through its return value. While we often focus on the buffer where the text is stored, the function itself returns a pointer. If the read is successful, it returns the address of your buffer. If it fails or hits the end of the file, it returns NULL.

Why Checking Matters

Think of fgets like a delivery person. If you ask them to bring you a package and they come back empty-handed, you shouldn't try to open the package they didn't bring. In C, if fgets returns NULL and you try to process the buffer anyway, you are processing "garbage" data left over from a previous operation or potentially accessing memory you shouldn't.

Checking for NULL is your way of asking: "Did the delivery actually arrive?"

The Implementation

Most professional C code wraps fgets in a while loop or an if statement. This ensures the program only proceeds if data was actually captured.

#include <stdio.h>

int main() {
    FILE *file = fopen("notes.txt", "r");
    char buffer[100];

    if (file == NULL) {
        return 1;
    }

    // fgets returns NULL when it hits the end of the file
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Line captured: %s", buffer);
    }

    printf("\nEnd of file reached or error occurred.\n");
    fclose(file);
    return 0;
}

In the example above, the loop continues as long as fgets finds data. The moment it hits the end of the file, it returns NULL, the condition becomes false, and the loop ends gracefully. Without this check, your program might enter an infinite loop or print the last line of the file twice.

Key takeaway

Always check if fgets returns NULL to ensure you aren't processing empty or invalid data at the end of a file.