2014-11-22 100 views
0

我想從現有的二進制文件中讀取數據,但我得到的只是一個段錯誤。 我以爲它可能來自結構,所以我使用了一個臨時數組,我嘗試填充值,但問題似乎來自ifstream讀取函數。任何人都可以幫我解決這個問題嗎?閱讀二進制文件時出現分段錯誤

bool RestoreRaspberry::RestorePhysicalAdress(TAddressHolder &address) { 
    mPRINT("now i am in restore physical address\n"); 
    /* 
    if (!OpenFileForRead(infile, FILENAME_PHYSICALADDRESS)){ 
     printf("\nRestoreUnit: Error open file Restore Physical Address\n"); 
     return false; 
    } 
    */ 
    ifstream ifile; 
    ifile.open(FILENAME_PHYSICALADDRESS, ios_base::binary | ios_base::in); 
    if (!ifile.is_open()) 
    { 
     printf("\nRestoreUnit: Error open file Restore Physical Address\n"); 
     return false; 
    } 

    printf("\nRestoreUnit: now trying to read it into adress structure\n"); 

    uint8 arr[3]; 
    //the problem occurs right here 
    for (int i = 0; i < cMAX_ADRESS_SIZE || !ifile.eof(); i++) { 
     ifile.read(reinterpret_cast<char *>(arr[i]), sizeof(uint8)); 
    } 

#ifdef DEBUG 
    printf("physical address from restoring unit: "); 
    /* 
    printf("%#x ", address.Address[0]); 
    printf("%#x ", address.Address[1]); 
    printf("%#x \n", address.Address[2]); 
    */ 
    printf("%#x", arr[0]); 
    printf("%#x ", arr[1]); 
    printf("%#x \n", arr[2]); 
#endif 
ifile.close(); 
    if (!ifile){//!CloseFileStream(infile)){ 
     printf("\nRestoreUnit: Error close file Restore Physical Address\n"); 
     return false; 
    } 

} 
+0

For循環的條件是最好使用''&&,但仍然不採取遠離['while(!eof())']不能預測抽取的事實(http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong)。 – 0x499602D2 2014-11-22 18:14:58

回答

3

這很難說,因爲你沒有提供編譯的例子,但是從它的外觀的問題是在這裏:

ifile.read(reinterpret_cast<char *>(arr[i]), sizeof(uint8)); 

您重新詮釋一個uint8char *。這意味着無論在arr[i](這是未定義的,因爲您沒有初始化它)而被保存的內容都被解釋爲將讀取值的地址。我相信這是你打算:

ifile.read(reinterpret_cast<char *>(&arr[i]), sizeof(uint8)); 

或者說是更明確:

ifile.read(reinterpret_cast<char *>(arr + i), sizeof(uint8)); 

你也應該改變循環條件使用&&;現在,如果文件中有超過300個字節,你會溢出arr陣列,並可能出現段錯誤有作爲:

for (int i = 0; i < cMAX_ADRESS_SIZE && !ifile.eof(); i++) { 
+0

對不起,我是新來的,忘了提高你的答案。但你的答案一直如此 – 2014-11-29 15:45:59