Write Structures to a Binary File using the function fwrite() - C File

C examples for File:File Write

Description

Write Structures to a Binary File using the function fwrite()

Demo Code

#include <stdio.h>
     struct biodata {
          char name[15];
          int rollno;
          int age;
          float weight;
     };/*from www . java2  s.c  o  m*/

int main(){
     int k = 0;
     char flag = 'y';
     FILE *fptr;
     struct biodata sa;
     fptr = fopen("C:\\Code\\data.dat", "wb");
     if (fptr != NULL) {
          printf("File data.dat is opened successfully.\n");
        
          while(flag == 'y'){
               printf("Enter name, roll no, age, and weight of agent: ");
               scanf("%s %d %d %f", sa.name,&sa.rollno,&sa.age,&sa.weight);
               fwrite(&sa, sizeof(sa), 1, fptr);
               fflush(stdin);
               printf("Any more records(y/n): ");
               scanf(" %c", &flag);
          }
          k = fclose(fptr);
          if(k == -1)
              puts("File-closing failed");
          if(k == 0)
              puts("File is closed successfully.");
     }
     else
         puts("File-opening failed");
     return(0);
}

Result


Related Tutorials