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

Formatted file input with fscanf

Formatted file input with fscanf

What you'll learn: How to extract specific types of data, like integers and strings, directly from a text file using the fscanf function.

The Digital Sieve

When you use fgetc or fgets, you are grabbing raw chunks of text. But what if your file is a list of high scores, like Player1 500? You don't just want the text; you want the name as a string and the score as a number you can perform math on.

Think of fscanf as a digital sieve. You tell C exactly what "shapes" of data you are looking for, and it filters the file to find them. If you tell it to look for a string followed by a number, it will skip over the spaces and tabs until it finds exactly that.

Using the Format String

The fscanf function works almost exactly like the scanf you use for the keyboard, but its first argument is a pointer to your file. You provide a "format string" using placeholders like %s for words, %d for integers, and %f for decimals.

Here is how you would read a simple data file containing a username and an age:

#include <stdio.h>

int main() {
    FILE *filePtr = fopen("users.txt", "r");
    if (filePtr == NULL) return 1;

    char name[50];
    int age;

    // Read a string and an integer from the file
    // The function returns how many items it successfully matched
    while (fscanf(filePtr, "%s %d", name, &age) == 2) {
        printf("Found user: %s, Age: %d\n", name, age);
    }

    fclose(filePtr);
    return 0;
}

Important Considerations

There are two things to keep in mind when using this tool:

  1. Whitespace is a separator: By default, %s stops reading as soon as it hits a space, tab, or newline. If your file has a full name like John Doe, fscanf with %s will only grab John.
  2. The Return Value: Always check the return value of fscanf. It returns the number of items it successfully read. If it expects two items but only finds one (or hits the end of the file), the loop should stop to avoid processing "garbage" data.

Using fscanf is the fastest way to turn a structured text file into variables your program can actually use.

Key takeaway

Use fscanf to automatically parse and convert text from a file into specific data types like integers and strings.