c - 如何在 C 中从 .dat 文件读取表

标签 c

我需要从 .dat (ASCII) 文件中读取一个表,该文件包含 3 列,行数是 .dat 文件中的第一行,然后将每列存储在单独的数组中。有人建议我使用 fscanf 但我不知道如何!

//this is the .dat file (ASCII format)
inname.dat 
//n -this is the first line in the .dat file and it represents number of rows in the table
2000 
//these are the different columns, each of which should be stored in
//a separate  array x[n],y[n],y[n]
-0.9210340500E+01  -0.1642608881E+01   0.1000000000E+01
-0.9204236984E+01  -0.1645367146E+01   0.1000000000E+01
-0.9198134422E+01  -0.1648124933E+01   0.1000000000E+01
-0.9192030907E+01  -0.1650882006E+01   0.1000000000E+01
-0.9185928345E+01  -0.1653640866E+01   0.1000000000E+01
-0.9179824829E+01  -0.1656393051E+01   0.1000000000E+01
-0.9173722267E+01  -0.1659148812E+01   0.1000000000E+01
-0.9167618752E+01  -0.1661900759E+01   0.1000000000E+01
-0.9161516190E+01  -0.1664654970E+01   0.1000000000E+01
-0.9155412674E+01  -0.1667405009E+01   0.1000000000E+01
-0.9149310112E+01  -0.1670155764E+01   0.1000000000E+01
-0.9143207550E+01  -0.1672905326E+01   0.1000000000E+01
-0.9137104034E+01  -0.1675654054E+01   0.1000000000E+01

最佳答案

如果建议使用fscanf,您可以打开文件,然后使用循环,例如

double varA, varB, varC;
while(fscanf(fil, "%lf%lf%lf", &varA, &varB, &varC) == 3) {
    // ...
}

一些人更喜欢的另一种方式是

char str[100];
double varA, varB, varC;
while(fgets(str, sizeof str, fil) != NULL) {
    if (sscanf(str, "%lf%lf%lf", &varA, &varB, &varC) != 3) {
        break;
    }
    // ...
}

关于c - 如何在 C 中从 .dat 文件读取表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55501714/

相关文章:

c++ - 从 C++ 使用 libcurl 的下载进度函数

c - 局部指针的段错误?

c - 解释器在 C 中输入

c - 为什么此 C 代码中使用的 IEEE-754 指数偏差是 126.94269504 而不是 127?

C 中的 char 数据类型

c - 重新编码 memset 时出现“段错误”

c - 如何检查向上和向下按钮是否在 native C 中被单击

c - 使用 C 中的 strtok 解析配置中的字符串

c - 当事先不知道输入大小但需要存储输入时,realloc 是在 C 中获取用户输入的唯一方法吗?

比较 INT_MAX 和 long 给出错误的结果