c - 如何用C语言从文件中提取数据

标签 c extract text-extraction

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

-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中提取数据并将每列的数字分配给一个 vector ;例如:

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

所有 6 列依此类推。

到目前为止我唯一知道的是我需要从做这样的事情开始:

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

有谁知道我应该做什么才能实现我的目标?

最佳答案

试试这个

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

请注意,您可能需要动态分配数据才能调整其大小。

关于c - 如何用C语言从文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28152424/

相关文章:

python如何识别 block html包含文本?

python - 根据文本语料库中的出现次数列出词汇表中的单词,使用 Scikit-Learn CountVectorizer

javascript - 使用 AppleScript/JavaScript 在大文本上提取 IP

c++ - 将 double 写入 EEPROM

c++ - 为什么 volatile 在多线程 C 或 C++ 编程中没有用?

python - 从具有特定模式的 txt 文件创建 Pandas DataFrame

Python从文件中提取可变长度文本

c++ - 可以在单个 CPU 指令中在 0 和 1 之间翻转位/整数/ bool 值的任何可能代码

c - 最适合 "block decomposition"的 MPI_Datatype ?

python - 如何从 Python 中的文件路径中提取文件夹路径?