从文件中读取并添加链接列表

时间:2016-12-06 15:08:04

标签: c file linked-list

我不知道为什么会造成分段错误。我不认为问题出在读取文件和编辑结构的代码中。头部是虚拟节点。我不知道是什么问题而且让我感到沮丧。有人可以帮我理解吗?

FOOD *New;
FILE *fp = fopen(strcat(fileName,".txt"), "r");
if(fp==NULL)    {
    printf("File %s is not found.\n", strcat(fileName,".txt"));
    return;
}
while(!feof(fp)){
    New = (FOOD*)malloc(sizeof(FOOD));

    for(i = 0; i < 9; i++){

        if(i == 0||i==1||i==2){
            fgets(scan, 256, fp);
            if(i==0)    strcpy(New->category, scan);
            else if (i==1)  strcpy(New->itemDescription, scan);
            else    strcpy(New->itemUnit, scan);
            //printf("NO");
        }

        else if (i==3||i==4||i==5){
            fscanf(fp, "%f", &fscan);
            fgetc(fp);
            if(i==3)    New->basePrice = fscan;
            else if(i==2)   New->comboPrice = fscan;
            else    New->upgradePrice = fscan;
            //printf("NO");
        }

        else{
            fscanf(fp, "%i", &iscan);
            fgetc(fp);
            if(i==6)    New->hierarchy = iscan;
            else if (i==7)  New->numberOfInitialInventory = iscan;
            else    New->numberOfPresentInventory = iscan;  
            printf("NO");
        }


    }
    if((*head)->next == NULL){
        (*head)->next = New;
        temp = New;
    }
    else{
        temp->next = New;
        temp = New;
    }


}



fclose(fp);

这是FOOD结构:

typedef struct foodtag{
char category[256];
char itemDescription[256];
char itemUnit[256];
int hierarchy;
int numberOfInitialInventory;
int numberOfPresentInventory;
float basePrice;
float comboPrice;
float upgradePrice;
struct foodtag *prev;
struct foodtag *next;
}FOOD;

2 个答案:

答案 0 :(得分:1)

(代表OP发布)

我已将while(!feof(fp))替换为其他条件,并将其伪装起来。

答案 1 :(得分:0)

您没有为category struct的<{1}}指针分配内存。

FOOD

编辑我对该问题的评论:

看看why is while feof file always wrong