如何在C语言中从文件中提取数据
我有一个.dat文件,其中包含6列N个数字,如下所示:如何在C语言中从文件中提取数据,c,extract,extraction,text-extraction,C,Extract,Extraction,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
-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中提取数据,并将每列的编号分配给一个向量;例如:
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;
}
#包括
#包括
#包括
#定义第256行的最大值
int main()
{
文件*文件;
浮动数据[最大行][6];
整数指数;
浮动*行;
file=fopen(“file.dat”、“r”);
if(file==NULL)
{
perror(“fopen()”);
返回1;
}
指数=0;
行=数据[0];
而(fscanf(文件,“%f%f%f%f%f%f”、&行[0]、&行[1]、&行[2]、&行[3]、&行[4]、&行[5])==6)
{
printf(“[%f;%f;%f;%f;%f;%f]\n”,行[0],行[1],行[2],行[3],行[4],行[5]);
行=数据[index++];
}
fclose(文件);
返回0;
}
请注意,您可能需要动态分配
数据
以调整其大小。阅读有关fscanfRead的信息,使用fgets()
,然后使用sscanf(“%lf%lf%lf%lf%lf”…)
Google“从文件c读取数据”或fgets
,strtok
和strtod
。实际上,您之前编写的一个更好,除了我必须做的几处更正(例如从%d到%f)之外,这一个对我来说看起来更可读,仅此而已。没有真正的区别。对你有用吗?当然!非常感谢你。。。这比我在谷歌上找到的更清楚