C fread() function : <stdio.h>



fread :

  1. This Function is Used in Binary Mode.
  2. Function Reads Block of Data from Binary Mode File and Assign it to the Region of Memory Specified.[i.e Reads Block of Data From Binary File and Assign it to Some Memory ]
  3. Returns : Total number of Values Read.

Syntax :

int fread(void *Buffer,int Size,int Count,FILE *ptr);
Parameters :
  • “Buffer” is Variable of Pointer Type.
  • Data read is Assigned to “Buffer” which Holds Starting Address of the Block.
  • Size Specifies the Size in Bytes of Individual Data Item being read.
  • Count Specifies “Number of Items to Be Read“.

Examples :
1. To Write Variable x of type Float to File

float x;
FILE *fptr;
int fread(&x,sizeof(x),1,fptr);

2. Write Structure to File

struct student
{
   char name[50];
   int roll;
};
main()
{
FILE *fptr;
struct student st[20];
int num;
if((fptr = fopen("ip.txt","wb+"))==NULL)
  {
  printf("\nError in Opening File");
  exit(0);
  } 
printf("How many Students : ");
scanf("%d",&num);

for(i=0;i<num;i++)
  {
  printf("\nEnter the Name and Roll Number");
  scnaf("%s %d",st.name,&st.roll);
  fwrite(&st,sizeof(st),1,fptr);
  }
//Structure is Written on File
//Now Read File
if((fptr = fopen("ip.txt","rb"))==NULL)
  {
  printf("\nError in Opening File");
  exit(0);
  } 

while((fwrite(&st,sizeof(st),1,fptr))
{
 printf("\nName : %s",st.name);
 printf("\nRoll : %d",st.roll);
}
fclose();
getch();
}