c++ - fseek 和 fscan 从 C++ 中的 .DAT 文件给出错误的结果

标签 c++ fopen scanf fseek fgetc

我有一个不断更新的 .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))", &timestep, &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/

相关文章:

c - scanf() 和 printf() 中的字符串变量名之前的 & 符号或没有 & 符号?

python - 基于 python 版本的 C++ python 扩展的输出差异

c++ - 程序以信号 25 终止,时间 = 0.06 秒 mem =3340KB

c++ - 在 Arduino 上使用 sscanf() 将最后一个字节归零

c - 文件、fopen 等...错误。文件为空

ios - iOS,fopen挂起/卡住

c - 使用 sscanf 解析无效

c++ - 在 Singleton 设计模式的情况下,我们如何使析构函数私有(private)化?

c++ - 模板命名

c++ - 读取文本文件 - fopen 与 ifstream