如何从C中读取.dat文件中的表

问题描述 投票:0回答:1

我需要从.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
c
1个回答
0
投票

如果建议是使用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;
    }
    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.