Files - 8 Demonstrating fscanf() function

/* Program to demonstrate the use of fscanf() function to read student details from the file and print the same*/

#include< stdio.h >

/* To learn more about structures, http://sridhanvantari.blogspot.com/2013/10/structures.html */
struct student
{
int rno;
char name[30];
};

main()
{
FILE *fp;
char c;
int choice;
struct student s;


/* To learn more about fopen(), http://sridhanvantari.blogspot.com/2013/12/files-1-file-handling.html */
 
fp=fopen( "Yourname.txt","r");
while( 1 )
{ 

/* To know more about syntax and parameters of fscanf(), http://sridhanvantari.blogspot.com/2013/12/fprintf-function-it-is-similar-to.html */


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


  if(fp==EOF) break;  /* To know about break, http://sridhanvantari.blogspot.com/2013/09/break-and-continue-keyword.html */

  printf( " \n  %d \t %s ", s.rno, s.name );
}

fclose(fp);
}

 
   In the above program initially we have declared a structure to hold the student details like rno and name. You can still expand the structure to hold more details. Variables are declared for pointer to file fp, a character variable c, an integer variable choice and a structure variable s to access structure  members.  Using fopen() function we are opening a file by name yourname.txt(you can replace yourname with your own file name)  in read mode.( To know more about file modes http://sridhanvantari.blogspot.com/2013/12/files-1-file-handling.html ) In a loop fscanf() reads data from file stream specified by pointer to file fp and stores into the additional arguments s.rno and s.name. Then using printf() function it is being printed on the standard output. Every iteration of a loop fetches a single record from the file. It repeats this process until it reaches EOF.  At last file is closed using fclose(fp).

Comments