SyntaxError101
SyntaxError101

Reputation: 69

How can I read an array of data from a text file in my code in C programming?

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);

Upvotes: 0

Views: 50

Answers (2)

user3629249
user3629249

Reputation: 16540

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++;
}

Upvotes: 0

Pablo
Pablo

Reputation: 13570

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;
}

Upvotes: 1

Related Questions