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

CServer Side ProgrammingProgramming

Problem

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

Solution

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

Syntax

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

Example

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.

Syntax

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

Example

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

Program

#include<stdio.h>
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\n", 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\n", i+1);
      fread (&s[i], sizeof (s[i]) ,1,fp);
      printf("student number = %d\n", s[i]. sno);
      printf("student name = %s\n", s[i]. sname);
      printf("marks = %f\n", s[i]. marks);
   }
   fclose(fp);
   getch( );
}

Output

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
raja
Published on 06-Mar-2021 07:45:52
Advertisements