Explain the functions fread() and fwrite() used in files in C


Write a C program for storing the details of 5 students into a file and print the same using fread() and fwrite()


The fread() function reads the entire record at a time.


fread( & structure variable, size of (structure variable), no of records, file pointer);


struct emp{
   int eno;
   char ename [30];
   float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);

The fwrite() function writes an entire record at a time.


fwrite( & structure variable , size of structure variable, no of records, file pointer);


struct emp{
   int eno:
   char ename [30];
   float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);


struct student{
   int sno;
   char sname [30];
   float marks;
   char temp;
main ( ){
   struct student s[60];
   int i;
   FILE *fp;
   fp = fopen ("student1.txt", "w");
   for (i=0; i<2; i++){
      printf ("enter details of student %d
", i+1);       printf("student number:");       scanf("%d",&s[i].sno);       scanf("%c",&s[i].temp);       printf("student name:");       gets(s[i].sname);       printf("student marks:");       scanf("%f",&s[i].marks);       fwrite(&s[i], sizeof(s[i]),1,fp);    }    fclose (fp);    fp = fopen ("student1.txt", "r");    for (i=0; i<2; i++){       printf ("details of student %d are
", i+1);       fread (&s[i], sizeof (s[i]) ,1,fp);       printf("student number = %d
", s[i]. sno);       printf("student name = %s
", s[i]. sname);       printf("marks = %f
", s[i]. marks);    }    fclose(fp);    getch( ); }


enter details of student 1
student number:1
student name:pinky
student marks:56
enter details of student 2
student number:2
student name:rosy
student marks:87
details of student 1 are
student number = 1
student name = pinky
marks = 56.000000
details of student 2 are
student number = 2
student name = rosy
marks = 87.000000

Updated on: 06-Mar-2021

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started