我有一个不断更新的 .dat 文件。我想从文件中的最新行获取数据。但我得到的结果不准确。这是我的文件.DAT:
# Time forces(pressure, viscous) moment(pressure, viscous)
0.005 (((2 10 4) (3 6 0)) ((12 60 -13) (4.88 0.5 -0.32)))
0.01 (((2 20 2) (4 7 3)) ((0.0024 1 -70) (40 6000 -1200)))
这是 C++ 代码:
#include <iostream>
#include <fstream>
#include <string>
int main ()
{
FILE * force;
force = fopen("file.dat", "r");
float timestep;
float fxp;
float fyp;
float fzp;
float fxv;
float fyv;
float fzv;
float mxp;
float myp;
float mzp;
float mxv;
float myv;
float mzv;
char c;
fseek(force,-285,SEEK_END);
while(c != '\n')
{
c = fgetc(force);
}
fscanf(force, "%f ((%f %f %f) (%f %f %f)) ((%f %f %f) (%f %f %f))", ×tep, &fxp, &fyp, &fzp, &fxv, &fyv, &fzv, &mxp, &myp, &mzp, &mxv, &myv, &mzv);
fclose(force);
float ftotal = fxp + fxv;
std::cout << "Here is f_total = " << ftotal << " N" << std::endl;
return 0;
}
结果如下:
Here is f_total = 0 N
显然这是错误的。它必须是 2 + 4 = 6。
最佳答案
您的 fscanf
格式字符串是:
"%f ((%f %f %f) (%f %f %f)) ((%f %f %f) (%f %f %f))"
但应该是:
"%f (((%f %f %f) (%f %f %f)) ((%f %f %f) (%f %f %f)))"
编辑:这很可能不是最好的方法(向后 2,向前 1)但检查它是否适用于此更改:
fseek(force, -1, SEEK_END);
while (c != '\n')
{
c = fgetc(force);
fseek(force, -2, SEEK_CUR);
}
关于c++ - fseek 和 fscan 从 C++ 中的 .DAT 文件给出错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42354902/