如何从C中的文件中提取数据 [英] How to extract data from a file in C

查看:124
本文介绍了如何从C中的文件中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.dat文件,其中包含6列N个数字,如下所示:

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
............  ............  ............  ............  ...........  ...........

我想用 C 语言编写代码,以便从file.dat中提取数据,并将每列的编号分配给矢量;例如:

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

以此类推,全部6列.

到目前为止,我唯一了解的就是我需要做这样的事情:

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?

推荐答案

尝试一下

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

请注意,您可能需要动态分配data才能调整其大小.

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

这篇关于如何从C中的文件中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆