将文本文件中的双精度数据复制到C语言的数组中

时间:2018-11-30 11:17:32

标签: c arrays file text double

我有一个这样的257点文本文件

3.78135
2.84681
2.81403
2.54225
3.10854
  ...

,我想读取此数据并将其复制到数组中。在类似的回答问题的帮助下,我这样写:

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

int max_read = 258;
double phi[max_read];
FILE *stream;
stream = fopen("namefile.txt", "r");

if (stream == NULL) {
  print ("! Cannot open file %sn", "namefile.txt\n"); 
  exit(1);
} else{
  int m = 0;
  while(m<max_read) {
    phi[m] = // But I still don't know how write the correct value into the array. 
    m++;
  }
}

我也想执行此读取复制过程,直到文件结束。

1 个答案:

答案 0 :(得分:4)

这应该可以解决我的问题。

if (stream == NULL) {
    fprint("! Cannot open file %sn", "namefile.txt\n");
    exit(1);
} else{
    int m = 0;
    while (fscanf(stream, "%lf\n", &phi[m])){
        m++;
    }
}