我有一個二進制檔案,我想一次處理一個位元組。這是我讀取檔案的第一個字符的內容:
ifstream file("input.dat", ios::binary);
unsigned char c;
file >> c;
但是,當我使用除錯器單步執行此代碼時,c盡管0x00檔案的第一個(也是唯一一個)字符是0x0A. 事實上,任何其他字符也完全被忽略。
如何從該檔案中讀取單個位元組?
uj5u.com熱心網友回復:
使用std::istream::get或std::istream::read。
char c;
if (!file.get(c)) { error }
int c = file.get();
if (c == EOF) { error }
char c;
if (!file.read(&c, 1)) { error }
最后:
unsigned char c;
if (!file.read(reinterpret_cast<char*>(&c), 1)) { error }
uj5u.com熱心網友回復:
請確保該檔案存在。在從流中讀取之前,您不會檢查任何錯誤。例如,您可以:
ifstream file("input.dat", ios::binary);
if(!file.is_open())
{
throw std::runtime_error("invalid path");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419329.html
標籤:
