我正在研究一个具有读取数据文件的函数的大型项目。但是,在某些测试代码中,该文件不存在,因此在创建时会创建一个空文本文件。我写了下面的代码来弥补这个事件:fscanf读取空文件时崩溃
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做的事情吗?谁能帮我吗?
这些变量像'power_down_type'有什么类型? 'int'? 'INT *'? –
我们如何知道文件能够正确打开?我们如何知道缺少的&&address - 运算符是否正确,并且'struct'包含指针?请发布显示问题的[Minimal,Complete和Verifiable示例](http://stackoverflow.com/help/mcve)。在第二个块中,你有'bootstatus-> power_down_type = 0;'这表明它们是值而不是指针。 –
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; –