fscanf() function in C is another important function in file handling in C programming which is used to read all types of data stored in the file.

What is fscanf() function in C?

Fprintf() function in C writes a mixed type of data to the file similarly fscanf() function in C reads the mixed type of data from the file.
As we know different file handling functions to read character, string and integer type of data from the file. but one file can contain a different type of data so to read the mixed type of data to file fscanf is used.
fscanf() function in C:– This function is used to read the mixed (different)type of data from the File.

fscanf() function in C
fscanf() function in C

fscanf Syntax in c
fscanf(FILE *fp,”format _specifier”, variable list);

In the above syntax, we can see fscanf function has 3 parameters which are as follows
1. FILE *fp :- The first parameter is file pointer which is a pointer to file which holds the address of the file.

2. Format specifier:- second parameter is format specifier which contains different format specifier for a different type (example:- for integer %d, for float %f )

3. Variable list:- This is list of variable which we want to read from the file.
The syntax for fscanf is the same as scanf except fscanf accept first parameter file pointer which points to file.

fscanf function is the same as scanf function, fscanf function reads data from file whereas scanf reads data from standard output screen.
fprintf is used to write a mixed type of data to file.

Why fscanf() function?

The file is a collection of different types of data. Suppose if we want to read a combination of data (character and integer) then there are two ways to do this:

1. Use fgetc() function to read character and after that use getw() to read an integer from file.
2. Use fscanf() function to read both characters and integers from the file.
Obviously the second option is the better one to read data from the file.

Program to demonstrate fscanf function


void main()


FILE *fp;

int no;

char name[10];

printf ("\nopening file in read mode");

fp=fopen("technical.txt","r");. //Opening file in read mode

//Reading no and name from file

printf ("\n Read data using fscanf function from file");

fscanf (fp,"%d.%s",&no,&name);

printf ("\n No=%d Name=%s",no,name);



Program description: –
In the above program, we read the integer and string data from a file .

1. First, we open file in reading mode. fopen(“technical.txt”,”r”) opens the file in reading mode.
2. Next write fscanf (fp,”%d.%s”,&no,&name) which reads the integer type data from a file and store it to no variable and string data stored in the name variable.
3. Let us assume file technical.txt file contains data 1 technical in a file. 01 is stored in no and Defineloop in the name.
4. Now we print that data from file to output screen using printf function.

Output: –

fscanf() function in C

Write A Comment