Search code examples
cstructbinaryfiles

How to read a binary file to a structure in C


I have this structure called product that I am trying to read from a binary file to fill in this function:

void reading(FILE *fp){

  Product *obuff = malloc(sizeof(Product));
  fread(obuff->code, sizeof(obuff->code), 1, fp);
  fread(obuff->name, sizeof(obuff->name), 1, fp);
  fread(obuff->quantity, sizeof(obuff->quantity), 1, fp);
  fread(obuff->price, sizeof(obuff->price), 1, fp);   

  printf("%s %s %d %.2f\n", obuff.code, obuff.name, obuff.quantity, obuff.price);
}

when I try to compile I get errors saying that I cannot pass arguments because of wrong data types. Is there a way to read to structures from Binary files or am I just doing something wrong here?

Structure:

#pragma pack(2)
struct product {
   char code[15];
   char name[50];
   short int quantity;
   double price;
};
#pragma pack()

typedef struct product Product;

Solution

  • You have to pass pointers to have fread() read data.

    void reading(FILE *fp){
    
      Product *obuff = malloc(sizeof(Product));
      fread(&obuff->code, sizeof(obuff->code), 1, fp);
      fread(&obuff->name, sizeof(obuff->name), 1, fp);
      fread(&obuff->quantity, sizeof(obuff->quantity), 1, fp);
      fread(&obuff->price, sizeof(obuff->price), 1, fp);
    
      printf("%s %s %d %.2f\n", obuff->code, obuff->name, obuff->quantity, obuff->price);
      free(obuff); /* free whatever you allocated after finished using them */
    }