Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 813
s d Avatar asked Sep 23 '22 02:09

s d


1 Answers

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 */
}
like image 179
MikeCAT Avatar answered Dec 09 '22 11:12

MikeCAT