OK, so then it never hits the EOF because it never moves beyond the line that doesn't obey the format. It just stays on that line, keeps returning a 1, and loops forever.
Now if I want to handle that error, a new problem crops up. Here, I save the return value of fscanf, and on the successful runs where the coords.txt file is valid, for some reason fscanf STILL only returns a 1 (rather than a 2), even if it reads both values successfully. So the program works as expected, but I can't tell the user there's a problem with the input file because I can't use "if(scanout!=2)". For example, the new code:
Code:
#include <stdio.h>
int main ()
{
float xtemp, ytemp;
FILE *pFile;
int scanout;
int n;
// Open the file with the coordinates and check that it opened OK.
pFile = fopen("coords.txt","r");
if(pFile == NULL)
{
printf("The file coords.txt does not exist.\n");
printf("Please create this file before running the program again.\n");
return 1;
}
// Now read formatted pairs until you hit the end of file
n = 0;
while(scanout=fscanf(pFile, "%f %f", &xtemp, &ytemp) != EOF)
{
// Handle a bad file
// if(scanout != 2)
// {
// printf("Invalid coordinate file. Please check format.\n");
// printf("No commas, please...\n");
// return 1;
// }
n++;
printf("Line %i: (%f,%f)...%i\n", n, xtemp, ytemp, scanout);
}
printf("There are %i coordinate pairs.\n", n);
return 0;
}
This executes as follows (for the valid non-comma input file):
Code:
Line 1: (4.234000,-23.430000)...1
Line 2: (0.111000,0.222000)...1
Line 3: (-3.000000,4.000000)...1
There are 3 coordinate pairs.
Now it reads all the values correctly, but fscanf still only returns a 1. If I uncomment the error-handling code, it will print that error message every time, even for the same coords.txt file. Why would this happen?
Thanks again!