Difference Between scanf() and fscanf() in C

Get Certified in C Programming and Take Your Skills to the Next Level

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);
     } 
}

 

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *