fscanf() Function in C

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.

Expected Output:

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.

Leave a Comment

%d bloggers like this: