Reputation: 3
I have a file,examplefile.txt, with data like this:
0.000 3.142
3.142 4.712
4.712 1.571
I am trying to read only the values in the second column. In an effort to do this I have been using the following code.
#include <stdio.h>
#include <float.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int main(int argc, const char * argv[])
{
double tempvalue;
int a,b;
FILE *file;
char *myfile=malloc(sizeof(char)*80);
sprintf(myfile,"examplefile.txt");
if (fopen(myfile,"r")==NULL)
{
}
else
{
file=fopen(myfile,"r");
for (a=0;a<3;a++)
{
for (b=0;b<2;b++)
{
printf("a=%d\n",a);
fscanf(file,"%lf",&tempvalue);
if (b==1)
{
printf("%lf\n",tempvalue);
}
}
}
}
}
However,this only returns the value 1.571 every time. I can't store all of the values because the actual file I'm using contains too many values to store. I have not been able to find a solution for this problem yet.
Upvotes: 0
Views: 37
Reputation: 11728
I suggest reading both, and just ignoring the first. Something like this
#include <stdio.h>
int main() {
float v1, v2;
FILE* file = fopen(myfile, "r");
if (file == NULL) {
perror("open failed");
return -1;
}
while(fscanf(file, "%f %f", &v1, &v2) == 2) {
print("read %f\n", v2);
}
return 0;
}
Upvotes: 2