I have create a struct and it has its id number, its value, and its status.
I have a file that consist of the data(1 199 0 2 199 1…) 1 its the number, 199 is the value, 0 is the status and keep going like this…
I have used 1 function called filldata() to read 3 numbers at a time, which are for example, 1 199 0 and then put it into the passed element of a struct array.
And then, i used another function to call the this function to fill up the struct array.
The fillAll function will return the set of data tha.t had been copied from the file to the struct array
But i received a segmentation fault. Any idea why?
The codes explain better:
int filldata(struct Data_point *a, const char *filelocation)
{
FILE *f;
if((f=fopen(filelocation,"r"))==NULL)
printf("You cannot open");
if( fscanf(f, "%ld%lf%d", &(a->sampleNumber), &(a->value), &(a->status)) == 3)
return 1;
else
return 0;
}
int fillAll(struct Data_point *a, const char *filelocation)// I will pass the struct array and the location of my file string
{
int index=0;
while(filldata(&a[index], filelocation))
index++;
return index;
}
you repeatedly open filename
filelocationbut never close the file handlef. You would keep reading the first line over and over again and eventually run out of filehandles.You can change filldata to take the file pointer check the snippet below i have added
some additional checks , you also need to check the
size of Data_point *ais within theallocated range as you fill it up