My data is as follows:
0.05 1.3
0.09 1.8
0.12 1.9
I create two variables x and y to store them respectively.
FILE *fp_data;
double *x;
double *y;
int data_size;
char ch;
int i;
fp_data = fopen(path, "r");
while( ( ch = fgetc(fp_data)) != EOF) if(ch=='\n') ++data_size;
if (!fp_data)
{
printf("Data file cannot open...\n");
exit(1);
}
else
{
x = (double*)malloc(data_size * sizeof(double));
y = (double*)malloc(data_size * sizeof(double));
printf("\n%d\n\n", data_size);
for (i = 0; i < data_size; ++i)
{
fscanf(fp_data, "%lf %lf\n", &x[i], &y[i]);
}
fclose(fp_data);
for (i = 0; i < data_size; ++i)
{
printf("%d- %f %f\n", i, x[i], y[i]);
}
}
I notice that my results are wrong like:
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
However, if I remove thewhile( (ch = fgetc(fp_data)) != EOF ) if(ch=='\n') ++data_size;
code and set data_size
manually, then everything is fine.
Does anyone know what is the problem of the fgetc
code?