fscanf function is another important function in file handling in c.
In this tutorial we are going to learn fscanf() function,how to use fscanf() function,why fscanf function is used.
As we know different file handling function to read character,string and integer type of data to file.but one file can contain different type of data so to read mixed type of data to file fscanf is used.
fscanf() function :- This function is used to read mixed (different)type of data from the File.
fscanf Syntax in c
fscanf(FILE *fp,”format _specifier”, variable list);
In above syntax we can see fscanf function has 3 parameter which are as follows
- FILE *fp :- First parameter is file pointer which is pointer to file which holds address of file.
- Format specifier :- second parameter is format specifier which contains different format specifier for different type (example:- for integer %d ,for float %f )
- Variable list :- This is list of variable which we want to read from file.
Syntax for fscanf is same as scanf except fscanf accept first parameter file pointer which point to file.
fscanf function is same as scanf function, fscanf function reads data from file whereas scanf reads data from standard output screen.
fprintf is used to write mixed type of data to file.
Program to demonstrate fscanf function
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");
printf ("\n No =%d Name=%s",no,name);
- In above program we read the integer and string data from file .
- First we open file in read mode.fopen(“technical.txt”,”r”) opens the file in read mode.
- Next write fscanf (fp,”%d.%s”,&no,&name) which reads the integer type data from file and store it to ni variable and string data stored in name variable.
- Let us assume file technical.txt file contain data 1 technical in file . 1 is stored in no and technical in name.
- Now we print that data from file to output screen using printf function.
opening file in read mode
Read data using fscanf function from file
No =1 .Name = technical