0

I have to write a function that will read an array of structures of type Product with data from a binary file.This file contains the number of products - nr and a number of articles of type Product. What's wrong? Thank you in advance!

#define SIZE 30

typedef struc{
    int id;
    char[SIZE] name;
    float price;
}Product;

void create(Product *p, FILE *fptr)
{
    p = malloc(sizeof(Product));
    fread(p, 1, sizeof(Product), fptr);
}

int main(int argc, char* argv[])
{
    FILE *fptr = fopen(argv[1],"rb");
    Product *p;
    create(p, fptr);

    return 0;
}

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
  • Will work only if data has been saved as `fwrite(p, 1, sizeof(Product), fptr);`. How was created the file? – Frankie_C Aug 29 '15 at 11:33
  • 1
    Won't work *at all* if you expect to see `p` be anything determinate in `main()`. The assignment to `p` in `create` means nothing to the `p` in `main()`. And where is your code that tries to read the magnitude, then the array? This only reads *one* struct, then leaks it. – WhozCraig Aug 29 '15 at 11:38

1 Answers1

0

You have to modify it to something like this:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 30

typedef struct{
    int id;
    char name[SIZE];
    float price;
}Product;

int readproducts(Product *p, FILE *fptr, int nr)
{    
    if(nr != fread(p, sizeof(Product), nr, fptr))
      return -1;

    return 0;
}

int main(int argc, char* argv[])
{
    FILE *fptr = fopen(argv[1],"rb");
    int nr = 0;
    if(NULL == fptr) return -1;
        
    // First read number of products from file
    // Assuming this number is written as 4 byte integer - at the start of file
    if(fread(&nr, 4, 1, fptr) != 1)
       return -1;

    // Now, read the products
    Product *p = malloc(nr * sizeof(Product));
    if(-1 == readproducts(p, fptr, nr))
     return -1;
 
    fclose(fptr);
    return 0;
}

The way you had used malloc in your function was wrong, see here why.

PS. That said, binary writing/reading might not be portable across different computers.

Community
  • 1
  • 1
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90