0

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.

2
  • 6 values is too many? Are you writing one on each of your fingers? Of one hand? Commented Feb 18, 2015 at 20:05
  • No it isn't. My actual file contains 100,000,000 values in two columns of 50,000,000 values apiece. Commented Feb 18, 2015 at 20:06

1 Answer 1

2

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;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

while(fscanf(file, "%f %f", &v1, &v2) == 2) would ensure you read two values successfully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.