c - fscanf crashing while reading empty file -
i'm working on large project has function reads file of data. in test code however, file doesn't exist, , when it's created, creates empty text file. wrote following code compensate event:
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 boot status info 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 boot status members set 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; }
i know fscanf returns number of things reads, when run program , reaches empty file, program freezes. missing should doing eof? can me out?
arguments of fscanf (third , next) must pointers appropriate type. in simplest case can use & operator
hard problem, no automatic casting shorter int typed (char / byte)
ret = fscanf(f, "%s %d %d %d %d %d %d", bootstatus->timestamp, // string &bootstatus->power_down_type, // int ... );
this depends on declaration, int declaration allowed in sample
if there not integers, use temporary variable. in example timestamp different kind of integral type (byte , on)
int tmp1; ret = fscanf(f, "%s %d %d %d %d %d %d", bootstatus->timestamp, &tmp1 , ... ); bootstatus->power_down_type = tmp1;
breaking of rules give severe problems (depends on system, compilers etc)
my answer based on assumptions, not real declaration of structure, unknown @ moment of writing
Comments
Post a Comment