0
0
CHow-ToBeginner · 3 min read

How to Use fscanf in C: Syntax, Example, and Tips

In C, fscanf reads formatted input from a file stream. You provide the file pointer, a format string, and pointers to variables where the read values will be stored. It works like scanf but reads from files instead of standard input.
📐

Syntax

The basic syntax of fscanf is:

  • FILE *stream: The file pointer to read from.
  • const char *format: A format string specifying the type and format of input.
  • ...: Pointers to variables where the read values will be stored.

fscanf returns the number of input items successfully matched and assigned, or EOF if an input failure occurs before any conversion.

c
int fscanf(FILE *stream, const char *format, ...);
💻

Example

This example shows how to open a file, read an integer and a float using fscanf, and print them.

c
#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "r");
    if (file == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }

    int number;
    float decimal;

    // Read an integer and a float from the file
    int result = fscanf(file, "%d %f", &number, &decimal);

    if (result == 2) {
        printf("Read integer: %d\n", number);
        printf("Read float: %.2f\n", decimal);
    } else {
        printf("Failed to read data correctly.\n");
    }

    fclose(file);
    return 0;
}
Output
Read integer: 42 Read float: 3.14
⚠️

Common Pitfalls

  • Not checking if the file opened successfully before using fscanf.
  • Not checking the return value of fscanf to ensure all expected inputs were read.
  • Passing variables instead of pointers to fscanf causes errors.
  • Format string mismatch with variable types leads to incorrect reading.
c
#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "r");
    if (!file) {
        return 1; // Always check file open success
    }

    int num;

    // Wrong: passing variable instead of pointer
    // fscanf(file, "%d", num); // This causes undefined behavior

    // Correct:
    fscanf(file, "%d", &num);

    fclose(file);
    return 0;
}
📊

Quick Reference

Tips for using fscanf:

  • Always open the file before reading.
  • Use the correct format specifiers like %d for int, %f for float.
  • Pass pointers to variables, e.g., &var.
  • Check the return value to confirm how many items were read.
  • Close the file after finishing reading.

Key Takeaways

Use fscanf to read formatted input from files by passing a file pointer, format string, and pointers to variables.
Always check if the file opened successfully before calling fscanf.
Check the return value of fscanf to ensure the expected number of inputs were read.
Pass pointers (like &var) to fscanf, not the variables themselves.
Match format specifiers in the format string exactly to the variable types you want to read.