C - используя feof() с хреном

Я должен прочитать некоторые двоичные файлы и сохранить их в динамическом списке. Когда я делаю это так, как я сделал (см. Ниже), и затем печатаю все продукты, которые я прочитал, консоль показывает мне 2 продукта с каждым полем, установленным на 0 (или отсутствует в случае массива). Я не могу понять, что я делаю неправильно, не могли бы вы помочь мне исправить это?

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;
}

0 ответов

Другие вопросы по тегам