我不知道爲什麼,但這會產生分段錯誤。我不認爲問題出在讀取文件和編輯結構的代碼中。頭是虛擬節點。我不知道這是什麼問題,這讓我很失望。有人能幫助我理解嗎?從文件中讀取數據並添加到鏈接列表中
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