我不知道为什么,但这会产生分段错误。我不认为问题出在读取文件和编辑结构的代码中。头是虚拟节点。我不知道这是什么问题,这让我很失望。有人能帮助我理解吗?从文件中读取数据并添加到链接列表中
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);
这里的食物结构:
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;
你应该发布,至少'FOOD'结构。最好有[MCVE](http://stackoverflow.com/help/mcve) – LPs
什么是FOOD结构? –
如果您遇到分段错误,您应该有一个核心文件(取决于ulimit)进行检查。如果没有,你可以在你的调试器下运行这个进程,它会停在segfault。 – Useless