How to extract data from a file in C

2020-08-02 11:00发布

I have a .dat file containing 6 columns of N numbers like so:

-4.997740e-01 -1.164187e+00 3.838383e-01 6.395961e+01 -1.938013e+02 -4.310365e-02
-1.822405e+00 4.470735e-01 -2.691410e-01 -8.528020e+01 -1.358874e+02 -7.072167e-01
9.932887e-01 -2.157249e+00 -2.303825e+00 -5.508925e+01 -3.548236e+02 1.250405e+00
-1.871123e+00 1.505421e-01 -6.550555e-01 -3.254452e+02 -5.501001e+01 8.776851e-01
1.370605e+00 -1.028076e+00 -1.137059e+00 6.096598e+01 -4.472264e+02 -1.268752e+00
............  ............  ............  ............  ...........  ...........

I want to write a code in C language where I extract the data from the file.dat and I assign the numbers of each column to a vector; for example:

V1=[-4.997740e-01;-1.822405e+00;9.932887e-01;-1.871123e+00;1.370605e+00];

and so on for all the 6 columns.

The only thing I know so far is that I need to start by doing something like this:

int main(){
FILE *fp;
fp=fopen("file.dat","r");
if (!fp){
    printf("Error\n");
    return 1;
}
return 0;
}

Does anyone know what I should do in order to accomplish my goal?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-08-02 11:35

Try this

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAX_ROW 256

int main()
{
    FILE  *file;
    float  data[MAX_ROW][6];
    int    index;
    float *row;

    file = fopen("file.dat", "r");
    if (file == NULL)
    {
        perror("fopen()");
        return 1;
    }

    index = 0;
    row   = data[0];
    while (fscanf(file, "%f%f%f%f%f%f", &row[0], &row[1], &row[2], &row[3], &row[4], &row[5]) == 6)
    {
        printf("[%f;%f;%f;%f;%f;%f]\n", row[0], row[1], row[2], row[3], row[4], row[5]);
        row = data[index++];
    }
    fclose(file);

    return 0;
}

note that you could need to make data dynamically allocated to be able to resize it.

查看更多
登录 后发表回答