C fwrite() function : <stdio.h>



fwrite :

  1. This Function is Used in Binary Mode.
  2. Function Writes Block of Data to Binary Mode File.[i.e Writes Block to Binary File]

Syntax :

int fwrite(void *Buffer,int Size,int Count,FILE *ptr);

Parameters :
  • “Buffer” is Variable of Pointer Type.
  • “Buffer” Holds Starting Address of the Block to be Written on File.
  • Size Specifies the Size in Bytes of Individual Data Item.
  • Count Specifies “Number of Items to Be Written Onto File“.

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

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

2 . Write Array of 100 Elements

float x[100];
FILE *fptr;
int fwrite(&x,sizeof(x),100,fptr);
  • 100 Specifies That Write 100 Floating Values to File Starting From Address Specified in Variable ‘x’.

3. 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
getch();
}