OverIQ.com

fscanf() Function in C

Last updated on July 27, 2020


The syntax of the function is:

Syntax: int fscanf(FILE *fp, const char *format [, argument, ...] );

The fscanf() function is used to read formatted input from the file. It works just like scanf() function but instead of reading data from the standard input it reads the data from the file. In fact, most of the arguments of fscanf() function are same as scanf() function, except it just needs an additional argument obviously enough a file pointer. On success, this function returns the number of values read and on error or end of the file it returns EOF or -1.

The following program demonstrates how to use fscanf() function to read formatted data from a file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<stdio.h>
#include<stdlib.h>

int main()
{
    FILE *fp;
    char name[50];
    int roll_no, chars;
    float marks;

    fp = fopen("records.txt", "r");

    if(fp == NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    printf("Testing fscanf() function: \n\n");
    printf("Name:\t\tRoll\t\tMarks\n");

    while( fscanf(fp, "Name: %s\t\tRoll no: %d\t\tMarks: %f\n"
                    , name, &roll_no, &marks) != EOF )
    {
        printf("%s\t\t%d\t\t%.2f\n", name, roll_no ,marks);
    }

    fclose(fp);
    return 0;
}

Expected Output:

1
2
3
4
5
Name: Tina      Roll no: 1       Marks: 45.00
Name: Nina      Roll no: 5       Marks: 89.00
Name: Tim       Roll no: 2       Marks: 49.00
Name: Jim       Roll no: 8       Marks: 41.00
Name: King      Roll no: 9       Marks: 59.00

How it works:

In lines 6, a structure pointer fp of type struct FILE is declared.

In line 7, an array of character name of size 50 is declared.

In line 8, two int variables roll_no and chars are declared.

In line 9, a variable marks of type float is declared.

In line 11, fopen() function is called with two arguments namely "records.txt" and "r". On success, it returns a pointer to file records.txt and opens the file records.txt in read-only mode. On failure, it returns NULL.

In lines 13-17, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.

In lines 19 and 20, we have two printf() statements which prints "Testing fscanf() function: \n\n" and "Name:\t\tRoll\t\tMarks\n" to the console.

In lines 22-26, the while loop is used along with fscanf() function to read the formatted data in the file and stores them in the variable name, roll_no and marks. The printf() statement is then user to print the data read from the file. The fscanf() keeps reading until EOF is encountered. When the end of file is encountered while condition becomes false and control comes out of the loop.

In line 28, fclose() function is called to close the file.