Wednesday, April 13, 2011

Use of fscanf function in C File handling


The scanf() function is used for formatted input from the standard input device. In a similar manner the fscanf() function is used for formatted input from files.
Syntax of fscanf() - fscanf(< file pointer >, "< format specifier >", < variable list >)
The following program will create a file and enter some values into the file using fprintf() function. Then the same program will read the values from the file using fscanf() function and will display on the monitor.

#include< stdio.h >
void main()
{
 FILE *ptr;
 int i,number;
 float balance;
 char ch,name[30],filename[10];
 clrscr();
 printf("Enter the file name:-");
 gets(filename);
 ptr=fopen(filename,"w");
 printf("\nEnter data\n");
 printf(" A/c No.  Name  Balance\n");
 for(i=0;i<3;i++)
 {
  fscanf(stdin,"%d%s%f",&number,name,&balance);
  fprintf(ptr,"%4d%10s%6.2f",number,name,balance);
 }
 fclose(ptr);
 ptr=fopen(filename,"r");
 puts(" Number   Name   Balance");
while(!feof(ptr))
 {
  fscanf(ptr,"%d%s%f",&number,name,&balance);
  printf("%4d%10s%6.2f\n",number,name,balance);
 }
 fclose(ptr);
 getch();
 }

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner