我想從現有的二進制文件中讀取數據,但我得到的只是一個段錯誤。 我以爲它可能來自結構,所以我使用了一個臨時數組,我嘗試填充值,但問題似乎來自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;
}
}
For循環的條件是最好使用''&&,但仍然不採取遠離['while(!eof())']不能預測抽取的事實(http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong)。 – 0x499602D2 2014-11-22 18:14:58