[英]How to extract data from a file in C
I have a .dat file containing 6 columns of N numbers like so: 我有一个.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
............ ............ ............ ............ ........... ...........
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; 我想用C语言编写一个代码,在其中我从file.dat中提取数据,并将每一列的编号分配给一个矢量; 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. 以此类推,对于所有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? 有人知道我应该怎么做才能实现我的目标吗?
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. 请注意,您可能需要动态分配
data
才能调整其大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.