FSCANF()

this function is used to read formatted input from a file stream, similar to how scanf() reads input from stdin.

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

 * stream: A pointer to a FILE object (e.g., from fopen())
 * format: A format string specifying the input to expect (e.g., "%d %s")
 * ...: Pointers to variables where the input will be stored

 * Reads input from the file stream, parses it according to the format specifiers
   (like %d, %s, %f, etc.), and stores the values in the provided variables.
 * Skips whitespace unless told otherwise.
 * Stops reading on input mismatch or EOF.
 * Returns the number of successfully matched and assigned input items.
 * Returns EOF on end-of-file or input failure.
#include <stdio.h>

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

    int age;
    char name[50];

    while (fscanf(fp, "%d %s", &age, name) == 2) {
        printf("Name: %s, Age: %d\n", name, age);
    }

    fclose(fp);
    return 0;
}

 * INPUT: file.txt
    42 Alice
    35 Bob
 * OUTPUT:
    Name: Alice, Age: 42
    Name: Bob, Age: 35

Last updated