简体   繁体   中英

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

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

this:

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

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

(we could be a LOT more help if you had followed the guilde lines about how to ask questions, for instance by posted a [mcve])

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM