How would I go about reading a binary file and assigning their values to a structure? Each structure with its content will be written to a csv file.
I have this data file, it's a list of struct product entries.
Here is the Product structure in an h file:
struct product {
char code[15];
char name[50];
short int quantity;
double price;
}
typedef struct product *Product;
And here is how I'm trying to read each line into the Product structure and writing it to the csv file:
File *fp;
File *outFile;
fp = fopen("products.dat", "rb");
outFile = fopen("allproducts.csv", "w");
Product p;
while (fread(p, sizeof(Product), 1, fp) == 1) {
fwrite(p->code, sizeof(p->code), 1, outFile);
}
I don't think I'm reading the file correctly because when I try writing to the file, all I get are the question marks in a box in the csv file.
fprintfinstead offwrite.pis pointer type. you not allocate for it. andsizeof(Product)is wrong.struct product pthe first time. But now that I've done that, my output is now correct, so thank you!