I've been doing this C program which requires reading .txt files and so on. There's been lots of warning about using !feof but I still don't understand where the limitations !feof could bring. I wonder if the fault on my code today is really on !feof
?
typedef struct City {
char cityName[20];
char cityID[10];
};
void readFiles() {
//preparing .txt file to read
char *txtMap = "map.txt";
char *txtPrice = "deliver_price.txt";
FILE *fmap = fopen(txtMap, "r");
FILE *fprice = fopen(txtPrice, "r");
City cityArr[20]; //I've defined the typedef struct before
int j, a = 0;
if (fmap == NULL || fprice == NULL || fmap && fprice == NULL) {
if (fmap == NULL) {
printf("\n\n\n\t\t\t\t\tError: Couldn't open file %s\n\n\n\n\n\n\n",
fmap);
printf("\n\n\n\t\t\t\t\tPress enter to continue\n\t\t\t\t\t");
return 1;
} else if (fprice == NULL) {
printf("\n\n\n\t\t\t\t\tError: Couldn't open file %s\n\n\n\n\n\n\n",
fprice);
printf("\n\n\n\t\t\t\t\tPress enter to continue\n\t\t\t\t\t");
return 1;
}
}
while (!feof(fmap)) {
City newCity;
fscanf(fmap, "%[^#]||%[^#]\n", &newCity.cityName, &newCity.CityID);
cityArr[a] = newCity;
a++;
}
printf("reading file succesfull");
fclose(fmap);
for (j = 0; j < a; j++) {
printf("\n%s || %s\n", cityArr[j].cityName, cityArr[j].cityID);
}
getch();
}
The text files need to be read:
New York||0
Washington D.C||1
Atlanta||2
Colombus||3
This program cannot read the files properly and making the program crash returning memory number. Anyone knows what's wrong with this program?
Sometimes when I tried fixing it, it says 'this part is a pointer, maybe you meant to use ->' error stuff. I don't know why this happen because in previous code, where I copied the file processing code part from, it doesn't happen like this.