c - fscanf 在读取空文件时崩溃

标签 c scanf satellite uclinux

我正在开发一个大型项目,该项目具有读取数据文件的功能。然而,在某些测试代码中,该文件不存在,因此在创建它时,它会创建一个空文本文件。我编写了以下代码来补偿此事件:

typedef struct system_boot_status_s{
  char timestamp[18];
  int power_down_type;
  int power_down_cause;
  int boot_number;
  int antenna_deployed;
  int images_captured;
  int beacon_count;
}system_boot_status_t;

////////////////////////////////

// Read the boot status info into the boot status struct
  ret = fscanf(f, "%s %d %d %d %d %d %d",
  bootstatus->timestamp,
  bootstatus->power_down_type,
  bootstatus->power_down_cause,
  bootstatus->boot_number,
  bootstatus->antenna_deployed,
  bootstatus->images_captured,
  bootstatus->beacon_count);

  if (ret != 7) // if 7 items weren't read
  {
    // Make sure all boot status members are set to 0
    snprintf(bootstatus->timestamp, BOOT_INFO_LEN, "xx-xx-xx-xx-xx-xx");
    bootstatus->power_down_type = 0;
    bootstatus->power_down_cause = 0;
    bootstatus->boot_number = 0;
    bootstatus->antenna_deployed = 0;
    bootstatus->images_captured = 0;
    bootstatus->beacon_count = 0;

    return -1;
  }

我知道 fscanf 返回它读取的内容的数量,但是当我运行这个程序并且它到达空文件时,我的程序就卡住了。我是否错过了应该用 EOF 做的事情?谁能帮我吗?

最佳答案

fscanf 的参数(第三个和下一个)必须是指向适当类型的指针。在最简单的情况下可以使用 & 运算符

难题,无法从较短的 int 类型(字符/字节)自动转换

ret = fscanf(f, "%s %d %d %d %d %d %d",
  bootstatus->timestamp, // string
  &bootstatus->power_down_type, // int
...
  );

这取决于声明,我的示例中只允许 int 声明

如果没有整数,则使用临时变量。在此示例中,时间戳是不同类型的整数类型(字节等)

   int tmp1;

    ret = fscanf(f, "%s %d %d %d %d %d %d",
      bootstatus->timestamp,
      &tmp1 ,
    ...
      );

    bootstatus->power_down_type = tmp1;

违反此规则会产生严重问题(取决于系统、编译器等)

我的回答是基于假设,而不是该结构的真实声明,在撰写本文时未知

关于c - fscanf 在读取空文件时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45680055/

相关文章:

ssl - 通过 Iridium 连接使用 SSL

google-maps - 中国 map - 卫星 map 和默认街道 map 哪个是正确的?这是否意味着地理编码结果是错误的?

c - 主功能 block 下面的函数在 1 种情况下给出错误,但在情况 2 中没有错误

c - 函数指针 WINAPI

c - 如何在 Windows 上截取屏幕截图并将其另存为 JPEG?

C++ 从字符串中获取小时和分钟

c - atomic_dec_if_positive 是如何原子化的?

c - 什么是 scanf ("%*s") 和 scanf ("%*d") 格式标识符?

c - 在此代码中除了使用 gets(c) 和 gets(s) 之外,还有什么替代方案?

programming-languages - 用于编写卫星任务程序的语言?