I would like to read a file that has the sample number, values and status(1.1, 23,0). I used a Struct to hold that information. I will pass the function struct array and the file location.
#include <stdio.h>
struct Data_point
{
long sampleNumber;
double value;
int status;
};
int filldata(struct Data_point *a, const char *filelocation)
{
FILE *f;
if((f=fopen(filelocation,"r"))==NULL)
{
printf("You cannot open");
}
fscanf(f, "%ld%lf%d", a.sampleNumber, a.value, a.status);
}
int main(void)
{
struct Data_point data[10];
filldata(data, "/home/alexchan/IntrotoC/rec11/dataPoints.txt");
return 0;
}
But, I got an error saying, “request for member not a structure”…
One problem is that the
filldata()is taking a pointer argument. So you use->to address members not “.”. Soa.sampleNumbershould bea->sampleNumberfor example.Another issue is that
filldata()is reading in a single struct, but you are passing it the pointer to the top of the array, which is synonymous with&(data[0]). So this function will just overwrite that first element if you call it repeatedly (which you didn’t). If you call it in a loop you will need to pass it in pointers to the individual array members:for(int i = 0; i < 10; ++i){filldata(&(data[i]), "/home/alexchan/IntrotoC/rec11/dataPoints.txt");
}
You could actually use
data + ias the first arg instead of&(data[i])but I like the latter as I find it more readable.