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++;
}
while(!feof(stream)) { ... }is wrong because of a logic problem, its not specific to strings or numbers. The logical pseudocode should bewhile (there is more data) { do somewthing with the data }When there is no more data, the loop terminates. Only at that point does it really make sense to check feof. For example, if your loop finished but you didn't make it to the end, maybe there is some invalid data in your file, or maybe a read error occured