2017-06-13 166 views
0

我想讀取數據的一個非常簡單的文件,看起來像這樣:分割方法故障()

1597 1 0 3 1 

使用下面的代碼:

void boot(){ 
FILE *f = fopen("shutdown.txt", "r"); 
    uint8_t timestamp = 0; 
    uint8_t power_down_type = 0; 
    uint8_t power_down_cause = 0; 
    uint8_t boot_number = 0; 
    uint8_t antenna_deployed = 0; 
    uint8_t images_captured = 0; 

    fscanf(f, "%u %d %d %d %d %d", &timestamp, &power_down_type, &power_down_cause, &boot_number, &antenna_deployed, &images_captured); 

    printf("timestamp: %u\n", timestamp); 
    printf("power_down_type: %d\n", power_down_type); 
    printf("power_down_cause: %d\n", power_down_cause); 
    printf("boot_number: %d\n", boot_number); 
    printf("antenna_deployed: %d\n", antenna_deployed); 
    printf("images_captured: %d\n", images_captured); 
} 

但是當我運行代碼,我得到一個SEGV錯誤。有人能幫我理解我在這裏做錯了什麼嗎?謝謝!

+1

'「%u」'期待一個'unsigned'。 'uint8_t'不是'unsigned'。使用'「%hhu」'。有關詳細信息,請查閱'fscanf()'文檔。 – chux

回答

1

%d讀取int%u讀取unsigned int,這兩者都是比uint8_t更大。通過寫入超過變量的大小發生未定義的行爲。 %hhu應該用於uint8_t