我正在从文件中读取数据orderedfile.txt。有时该文件具有以下形式的标题:
BEGIN header
Real Lattice(A) Lattice parameters(A) Cell Angles
2.4675850 0.0000000 0.0000000 a = 2.467585 alpha = 90.000000
0.0000000 30.0000000 0.0000000 b = 30.000000 beta = 90.000000
0.0000000 0.0000000 30.0000000 c = 30.000000 gamma = 90.000000
1 ! nspins
25 300 300 ! fine FFT grid along <a,b,c>
END header: data is "<a b c> pot" in units of Hartrees
1 1 1 0.042580
1 1 2 0.049331
1 1 3 0.038605
1 1 4 0.049181
Run Code Online (Sandbox Code Playgroud)
有时没有标题,数据从第一行开始。我的读取数据的代码如下所示。当数据从第一行开始但不存在标题时它会起作用。有办法解决这个问题吗?
int readinputfile() {
FILE *potential = fopen("orderedfile.txt", "r");
for (i=0; i<size; i++) {
fscanf(potential, "%lf %lf %*f %lf", &x[i], &y[i], &V[i]);
}
fclose(potential);
}
Run Code Online (Sandbox Code Playgroud)
以下代码将使用fgets()读取每一行。对于每一行,sscanf()用于扫描字符串并将其存储到双精度变量中。
请参阅 ideone 上的运行示例(使用标准输入)。
#include <stdio.h>
int main()
{
/* maybe the buffer must be greater */
char lineBuffer[256];
FILE *potential = fopen("orderedfile.txt", "r");
/* loop through every line */
while (fgets(lineBuffer, sizeof(lineBuffer), potential) != NULL)
{
double a, b, c;
/* if there are 3 items matched print them */
if (3 == sscanf(lineBuffer, "%lf %lf %*f %lf", &a, &b, &c))
{
printf("%f %f %f\n", a, b, c);
}
}
fclose(potential);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它正在使用您提供的标头,但如果标头中有一行,例如:
1 1 2 0.049331
Run Code Online (Sandbox Code Playgroud)
会出现,那么该行也会被读取。另一种可能性是搜索单词END headerif BEGIN headeris 存在于给定标题中,或者如果行数已知则使用行数。要搜索子字符串,可以使用
函数strstr() 。
| 归档时间: |
|
| 查看次数: |
2841 次 |
| 最近记录: |