0
我有一個二進制文件,其中包含10個整數讓我們說二進制。有什麼方法可以使用迭代器來檢查該文件嗎?到目前爲止,我只是從文件中處理這些數字並將它們放入數組中。但我可以避免使用數組或向量?有些事告訴我可能需要重載++和 - 。希望我的問題很清楚。使用迭代器瀏覽文件
我有一個二進制文件,其中包含10個整數讓我們說二進制。有什麼方法可以使用迭代器來檢查該文件嗎?到目前爲止,我只是從文件中處理這些數字並將它們放入數組中。但我可以避免使用數組或向量?有些事告訴我可能需要重載++和 - 。希望我的問題很清楚。使用迭代器瀏覽文件
使用任何std::istream
讀取文件,你可以使用std::istream_iterator
和定義自定義operator>>
使用std::istream.read()
讀取整數。例如:
struct binary_int
{
int32_t value; // or whatever type you need
};
std::istream& operator>>(std::istream &in, binary_int &out)
{
return in.read((char*)&out.value, sizeof(out.value));
}
{
std::ifstream inFile(...);
std::istream_iterator<binary_int> iter(inFile);
std::istream_iterator<binary_int> end;
while (iter != end)
{
// use iter->value as needed...
++iter;
}
}
將其讀入緩衝區。將緩衝區視爲一個數組。你確定他們是在右端格式?爲什麼要避免使用陣列,當他們是工作的正確工具? – tadman
@tadman這就是任務:( –
如果這是一個編碼挑戰,**得到編碼**。記住在C和C++數組和指針是同一枚硬幣的兩面。 – tadman