fprintf and fscanf in c

fprintf() and fscanf() in c

fprintf()

This function same as printf() but it write formated data into the file instead of the standard computer(screen). This function fpritnf() has same parameters as in printf() but in the fprintf() function has one extra parameter which is the pointer of FILE type. which point to the file to where the output is to be written. The pointer returns the number of characters output to the file on success and on error give EOF

.

Declaration:
fprintf(FILE *fptr,const char *format[arguments,…,..])

/* program to understand the use of fprintf() */
#include<stdio.h>
#include<stdlib.h>
int
main()
{
FILE *fptr;
char name[15];
int salary;
if ((fptr=fopen("rec","w"))==NULL)
{
printf("Error in opening file \n");
exit (1);
}
printf("Enter name and salary :" );
scanf("%s%d", &name,&salary);
fprintf(fptr," name is %s and salary %d",name,salary);
fclose(fptr);
return 0;
}

fscanf()

Declaration: fscanf(File *ptr,const char *format[.address,….]);

This function is similar to the scanf() function but it reads data from file instead of standard input, so it has one more parameter which is pointer of FILE type which point to the file from where data will read. so here its return number of arguments that were assigned some values on sucess and the EOF at end of file.

#include<stdio.h>
#include<stdlib.h>
struct student
{
char name[20];
float marks;
}stu;
int main()
{ FILE *fp;
if((fp=fopen("students","r"))==NULL)
{
printf("Error in opening file \n");
exit(1);
}
printf("NAME\t MARKS\n");
while(fscanf(fp,"%s %f",stu.name,&stu.marks)!=EOF)
printf("%s \t %f \n",stu.name,stu.marks);
fclose(fp);
return 0;
}