0

I gotta read some binary files and save them in a dynamic list. When I do it the way I did - see below -, and then print all the products I read, the console shows me 2 products with every field set to 0 (or missing in case of an array). I can't understand what I am doing wrong, could you please help me fixing it?

typedef struct product_temp{
    int code;
    char name[MAX_NAME];
    char category[MAX_CATEGORY];
    char provenience[MAX_PROVENIENCE];
    int quantity;
    float price;
    struct product_temp *next;
} product;

product *list_transfer(FILE *file){
    product *head, *current, *current_temp;
    int end = 0, i = 0, outcome;

    while(end == 0){
        if(i == 0){
            current = malloc(sizeof(product));
            if(current == NULL){
                fprintf(stderr, "Impossibile allocare memoria!\n");
                exit(6);
            }
            memset(current, 0, sizeof(product));
            head = current;
        }
        else{
            current->next = malloc(sizeof(product));
            if(current->next == NULL){
                fprintf(stderr, "Impossibile allocare memoria!");
                exit(6);
            }
            memset(current->next, 0, sizeof(product));
            current = current->next;
            memset(current, 0, sizeof(product));
        }
        if((outcome = fread(&current->code, sizeof(current->code), 1, file)) == 0){
            end = 1;
        }
        if((outcome = fread(&current->name, sizeof(current->name), 1, file)) == 0){
            end = 1;
        }
        if((outcome = fread(&current->category, sizeof(current->category), 1, file)) == 0){
            end = 1;
        }
        if((outcome = fread(&current->provenience, sizeof(current->provenience), 1, file)) == 0){
            end = 1;
        }
        if((outcome = fread(&current->quantity, sizeof(current->quantity), 1, file)) == 0){
            end = 1;
        }
        if((outcome = fread(&current->price, sizeof(current->price), 1, file)) == 0){
            end = 1;
        }
        if(feof(file)){
            end = 1;
            free(current);
        }
        i++;
    }
    return head;
}
Mazza
  • 3
  • 4

0 Answers0