【问题标题】:reading from a json file using fscanf() in c在 c 中使用 fscanf() 从 json 文件中读取
【发布时间】:2020-11-13 04:03:27
【问题描述】:

我想知道是否有人可以解释为什么它读取零以及如何修复它

#include <stdio.h>

int main(void) {
  FILE* f = fopen("text.json","r");
  int l,x=0;
  fscanf(f,"%d %d ",&l,&x);
  printf("%d %d ",l,x);
 
  return 0;
}

我的 text.json:

[ 1, 2, 3, 4 ]

运行时会打印两个 0。我真的不明白为什么或如何让它打印数字。

【问题讨论】:

  • man fscanf: If processing of a directive fails, no further input is read。在您的情况下,%d 告诉fscanf 匹配一个整数作为下一个输入。由于下一个输入是 [ 而不是整数,因此指令失败并且没有进一步的输入被读取。
  • 试试if (fscanf(f," [%d ,%d ,",&amp;l,&amp;x) == 2) success();

标签: c file-io


【解决方案1】:

使用fread 代替fscanf

char buffer[1024] = {0};

fread(buffer, 1024, 1, f);

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多