简体   繁体   中英

How read a large number of float from file?

I have a file with a large quantity of number and I need to read every single line, and then put every number in that line in an array.

This is two line of my file:

  7.7560198e+002  8.2334910e+002  9.7819197e+002  1.4330775e+003  3.0535763e+003  3.3218925e+003  1.7164341e+003  3.1848433e+003  4.9317846e+002  3.4466984e+002  4.7654154e+002  4.9282917e+002  9.5322001e+001  1.2369945e+002  5.3310001e+001  1.0394150e+002  3.1919280e+003  2.1591746e+003  2.1608040e+003  3.6585112e+003

  7.1244665e+002  1.4142187e+003  1.7148456e+003  1.3126353e+003  3.4328919e+003  2.8380069e+003  2.8432808e+003  3.6142229e+003  3.3866501e+002  3.9236491e+002  5.0149915e+002  5.9447907e+002  1.3568213e+002  5.9164038e+001  7.1649000e+001  1.3451865e+002  2.2922576e+003  1.8212714e+003  2.9237970e+003  5.1605066e+003

I tried with this code:

FILE *f = fopen(pathInput,"r");
if(f==NULL) {
    printf("Error\n");
    return -1;
}

int i, j, columnsNumber=0, rowsNumber=0;
char c; 
c = fgetc(f);

// count number of column with the first line
for(i=0;c != '\n'; i++) {
    if (c==' ') {
        while(c==' ')
            c = fgetc(f);
        numCol++;
    }
    c = fgetc(f);
}

// count the rows
while(!feof(f)){
    c = fgetc(f);
    if(c == '\n'){
        rowsNumber++;
    }
}

float input[(rowsNumber)* columnsNumber];

for(j=0; j< rowsNumber;j++){
    for (i = 0; i < columnsNumber; i++){
        fscanf(f, "%f ", input[i] );
    }
}

for(i=0;i<10; i++){
    printf("%f\n", input[i]);
}

fclose(f);

But it doesn't work and the I obtain this warning:

warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘float *’ [-Wformat=]
         printf("%f\n", input[i]);

In your code, you create an array of pointers to floats. You're actually looking to create an array of floats. That declaration would look like the following. Note the lack of a float * .

float input[rowsNumber * columnsNumber];

At that point, you'll get a warning from fscanf() . You're supposed to pass a pointer to an allocated piece of memory. So:

fscanf(f, "%f ", &input[j*columnsNumber + i]);

And, you'll also have problems because you are attempting to read the file twice. You'll want to either close and reopen the file, or reset the file to be looking at the beginning of the file with fseek() .

Finally, and I'm not 100% sure on this, but I think it's likely that between when you count the number of floats in a column and the number of floats in a row, you'll possibly miss one '\\n' character.

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