Read Structures Written to a Binary File using the function fread() - C File

C examples for File:File Write

Description

Read Structures Written to a Binary File using the function fread()

Demo Code

#include <stdio.h>
     struct biodata{
          char name[15];
          int rollno;
          int age;
          float weight;
     };/*w ww.ja va  2s .c o  m*/

int main(){
     int k = 0, m = 0;
     FILE *fptr;
     struct biodata sa;
     fptr = fopen("C:\\Code\\data.dat", "rb");
     if (fptr != NULL) {
          printf("File data.dat is opened successfully.\n");
          m = fread(&sa, sizeof(sa), 1, fptr);
        
          while(m != 0){
               printf("Name: %s, Roll no: %d, Age: %d, Weight: %.1f\n", sa.name, sa.rollno,sa.age, sa.weight);
               m = fread(&sa, sizeof(sa), 1, fptr);
          }
        
          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