I don't know why but this creates segmentation fault. I don't think the problem is in the code for reading in a file and editing a structure. The head is a dummy node. I don't know what is the problem and it frustrates me. Can someone help me understand?
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);
Here's the FOOD structure:
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;