0

我必须阅读一些二进制文件并将它们保存在动态列表中。当我按照我的方式进行操作时(见下文),然后打印我阅读的所有产品,控制台会向我显示 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;
}
4

0 回答 0