I've been given a task to read space separated float values from a data.txt file in C.
The file looks like this...
0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196
0.796078 0.800000 0.800000 0.796078
0.796078 0.800000 0.800000 0.796078
0.796078 0.800000 0.800000 0.796078
0.796078 0.800000 0.800000 0.796078
0.796078 0.800000 0.800000 0.796078
0.796078 0.800000 0.800000 0.796078
0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196
The middle two rows are constant. The task is to find when the 1st and 4th row are both in the range of 0.7 or above and keep a count of it. This is just a snippet of the file but here they're going above 0.7 for sometime so the count increments by one. The actual file has thousands of lines but only four columns.
I've tried it like this:
#include<stdio.h>
#include<stdlib.h>
int main()
{
float arr[4000][4];
int i, j, vals =0, count = 0;
FILE *fpointer;
char filename[10];
printf("Enter the name of the file to be read: ");
scanf("%s",filename);
fpointer = fopen(filename, "r");
if (fpointer == NULL)
{
printf("Cannot open file \n");
exit(1);
}
while(!feof(fpointer))
{
for(i=0; i<4000; i++)
{
for(j=0; j<4; j++)
{
fscanf(fpointer, " %f ", &arr[i][j]);
}
if (arr[i][0] >= 0.7 && arr[i][3] >= 0.7)
vals += 1;
else if (arr[i-1][0] >= 0.7 && arr[i-1][3] >= 0.7)
count += 1;
}
}
printf("number of counts: %d", count);
fclose(fpointer);
}
But I've been told to read the file line by line and then evaluate instead of storing into a large array as the program might crash if it's a large file.
Can you please assist me in doing so? I have similar larger files and I'm not sure how many lines they have.
Please let me know how can I read the values line by line & evaluate it at the same time.
Thank you in advance.