0

I have a code that reads a text file which has a bunch of numbers. I use the code below to access it but this only grabs the first line.

I have 99 other lines of data I want to access. How do I make it read the other 99 lines of data ?

fscanf(fp1,"%lf,%lf,%lf,%lf",&a,&b,&c,&d);
2
  • have you ever tried getting data line by line from the file and parsing every line data with fscanf ? Commented Mar 11, 2018 at 15:49
  • As I have mentioned there are 99 more rows of data to go through. I do not know how to do what you have mentioned efficiently. Commented Mar 11, 2018 at 15:51

2 Answers 2

1

As elia mentions in the comments, the best strategy is to read the whole line and then parse it with sscanf.

char buffer[1024];
while(fgets(buffer, sizeof buffer, fp1))
{
    if(sscanf(buffer,"%lf,%lf,%lf,%lf",&a,&b,&c,&d) != 4)
    {
        fprintf(stderr, "Invalid line format, ignoring\n");
        continue;
    }

    printf("a: %lf, b: %lf, c: %ld, d: %lf\n", a, b, c, d);
}

Another option is to keep reading until \n:

while(1)
{
    if(fscanf(fp1,"%lf,%lf,%lf,%lf",&a,&b,&c,&d) != 4)
    {
        fprintf(stderr, "Invalid line format, ignoring\n");
        if(clear_line(fp1) == 0)
        {
            fprintf(stderr, "Cannot read from fp1 anymore\n");
            break;
        }
        continue;
    }

    printf("a: %lf, b: %lf, c: %ld, d: %lf\n", a, b, c, d);

    if(clear_line(fp1) == 0)
    {
        fprintf(stderr, "Cannot read from fp1 anymore\n");
        break;
    }
}

and clear_line looks like this:

int clear_line(FILE *fp)
{
    if(fp == NULL)
        return 0;

    int c;
    while((c = fgetc(fp)) != '\n' && c != EOF);

    return c != EOF;
}
Sign up to request clarification or add additional context in comments.

Comments

0

this:

fscanf(fp1,"%lf,%lf,%lf,%lf",&a,&b,&c,&d);

hints that there are only 4 numbers per line in the input file.

The posted code suggests:

float a;
float b;
float c;
float d;

and that the numbers on the line are separated by commas

Suggest:

#define MAX_LINES 100

float a[ MAX_LINES ];
float b[ NAX_LINES ];
float c[ MAX_LINES ];
float d[ MAX_LINES ];

size_t i = 0;
while( i<MAX_LINES && 4 == fscanf( fp1, "%lf,%lf,%lf,%lf", &a[i], &b[i], &c[i], &d[i] )
{ 
    // perhaps do something with the most recent line of data
    i++;
}

Comments

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.