我不知道为什么会造成分段错误。我不认为问题出在读取文件和编辑结构的代码中。头部是虚拟节点。我不知道是什么问题而且让我感到沮丧。有人可以帮我理解吗?
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;
答案 0 :(得分:1)
(代表OP发布)。
我已将while(!feof(fp))
替换为其他条件,并将其伪装起来。
答案 1 :(得分:0)