-
EOF question, scanf also
I have a piece of code that currently only reads in one line of data from a file :
gcc myfile.c<data.dat
data.dat contains:
2 8 1101100
I'm using the scanf function to read in these values.
I want to be able to read in more than one line of the data file; I know I need to construct some sort of loop to read it but I'm not sure how.
Would it be a while(------ != EOF) ??
Please help
-
What about
while (fscanf (infile, "%d %d %d", x , y, z) != EOF)
anyway I assume you are using integers and the file continue to look follow same pattern. Anyway, use fscanf
-
Or use
while (fscanf (infile, "%d %d %d", x , y, z) == 3)
Or use fgets() to grab the line, and parse the data whilst its in memory.
-
>>while (fscanf (infile, "%d %d %d", x , y, z) != EOF)
This works fine if nothing happens in the middle of a conversion. scanf returns EOF if the end of the file is reached or if there's an error before any conversions, otherwise the number of successful conversions is returned. This is better
Code:
while (fscanf (infile, "%d %d %d", x , y, z) == 3)
Now you cover for all possible oopsies that can confuse your program :-)
-
>while (fscanf (infile, "%d %d %d", x , y, z) == 3)
Or even more likely:
while (fscanf (infile, "%d %d %d", &x , &y, &z) == 3)
I'm going to guess the prog has three ints, rather than 3 int pointers.