Site icon DataFlair

Difference Between scanf() and fscanf() in C

Program 1

// Program for scanf and fscanf 

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define clrscr() system("cls")
int main()
{
     int rno;
     char name[50];
     float per;
     FILE *fp=NULL;
     fp=fopen("c://mycfile/student.txt","w");
     clrscr();
     if(fp==NULL)
     printf("File not created.....");
     else
     {
     printf("Enter Roll No");
     scanf("%d",&rno);
     printf("Enter Name");
     scanf("%s",name);
     printf("Enter Percentage");
     scanf("%f",&per);
     fprintf(fp,"%d %s %f",rno,name,per);
     fclose(fp);
     printf("File created......");
     } 
}

Program 2

// Program for scanf and fscanf 

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define clrscr() system("cls")
int main()
{
     int rno;
     char name[50];
     float per;

     FILE *fp=NULL;
     fp=fopen("c://mycfile/student.txt","r");
     clrscr();
     if(fp==NULL)
     printf("File not found....");
     else
     {
        fscanf(fp,"%d %s %f",&rno,name,&per);
        
        printf("Roll No= %d",rno);
        printf("\nName= %s",name);
        printf("\nPercentage= %f",per);

        fclose(fp);
     } 
}

 

Exit mobile version