C Read Files

Saving data would be pointless if we could never get it back. In this lesson you will learn how to open a file and read the text stored inside it, line by line, using functions like fgets().

To read from a file, you open it in read mode ("r"). Remember that read mode does not create a file. If the file does not exist, fopen() returns NULL, so checking for NULL is even more important when reading than when writing.

Reading Line by Line with fgets()

The fgets() function reads one line of text from a file and stores it in a character array (a string). It needs three things: the array to fill, the maximum number of characters to read, and the file handle. It is a safe choice because it will never read more characters than your array can hold.

Read the first line of a file

#include <stdio.h>

int main() {
    FILE *fptr = fopen("greeting.txt", "r");
    if (fptr == NULL) {
        printf("The file does not exist.\n");
        return 1;
    }

    char line[100];
    // Read up to 99 characters into line
    fgets(line, 100, fptr);
    printf("First line: %s", line);

    fclose(fptr);
    return 0;
}

Most files have more than one line, so we usually read them inside a loop. The trick is knowing when to stop. When fgets() reaches the end of the file, it returns NULL, which is a perfect signal to end the loop.

Read a whole file with a loop

#include <stdio.h>

int main() {
    FILE *fptr = fopen("greeting.txt", "r");
    if (fptr == NULL) {
        printf("Could not open the file.\n");
        return 1;
    }

    char line[100];
    // Keep reading until fgets returns NULL (end of file)
    while (fgets(line, 100, fptr) != NULL) {
        printf("%s", line);
    }

    fclose(fptr);
    return 0;
}

Other Ways to Read

  • fgetc() reads a single character at a time, which is useful for scanning through a file character by character.
  • fscanf() reads formatted data, such as pulling an int or a float out of a file, similar to how scanf() reads from the keyboard.
  • fgets() is usually the safest and easiest choice for reading text one line at a time.
Note: The character arrays you read into must be large enough to hold a whole line plus the hidden end-of-string marker. If a line might be long, give your array plenty of room, such as 100 or 256 characters, to avoid cutting text off.
FunctionReadsReturns at end of file
fgetc()One characterEOF
fgets()One line (a string)NULL
fscanf()Formatted valuesEOF

Exercise: C Files

What does `fopen("data.txt", "r")` return if the file doesn't exist?