I'm writing a program in C, that is supposed to read arrays of doubles from files of arbitrary length. How to stop it at EOF? I've tried using feof, but then read the discussions:
Why is “while ( !feof (file) )” always wrong?
Then again they concern strings, not numbers. So when reading a file of the form "4 23.3 2 1.2", how to state the loop condition, so that my array A has all the numbers from the file and nothing more (also the iterator N = length of A)?
Here's the part of my code with feof, which produces one entry too many in A. The reallocation part is based on http://www.cplusplus.com/reference/cstdlib/realloc/ example.
int N = 0;
double *A = NULL;
double *more_space;
double buff = 0;
FILE *data;
data = fopen(data.dat,"r");
while(feof(data) == 0) {
fscanf(data, "%lg", &buff);
more_space = realloc(A, (N+1)*sizeof(double));
A = more_space;
A[N] = buff;
N++;
}
Answer
The return value of fscanf is -1 when you hit eof (or other problems) so try while(fscanf(…) >= 0)
for your outer loop. (Whether you accept a zero return value or not depends on how you want to handle bad data -- as other posters have pointed out, you will get 0 if no numbers are converted.
I like using the 'greater than or equals' test (instead of testing for ==1
) because it doesn't break if you change the scanf format to, say, read two items from the input line. On the other hand, you could argue that it's better to verify that you always read exactly the correct number of arguments, and it's better to have your program 'fail fast' as soon as you change the number of scant arguments, than to have some mysterious failure later on, if you get bad input. It's a matter of style, and whether this is throwaway code for an assignment, or production code..
No comments:
Post a Comment