gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:55:38 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com