C - 使用feof()与fread

时间:2015-01-29 11:01:42

标签: c fread 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 个答案:

没有答案