我需要读取一个包含标题和数据的二进制文件(一次性)。用 C++ 读取文件有不同的方法,我想知道哪种方法最快、更可靠。我也不知道是否reintrerpret_cast
是将原始数据转换为结构的最佳方法。
编辑:标题结构没有任何功能,只有数据。
ifstream File(Filename, ios::binary); // Opens file
if (!File) // Stops if an error occured
{
/* ... */
}
File.seekg(0, ios::end);
size_t Size = File.tellg(); // Get size
File.seekg(0, ios::beg);
这是没有 istreambuf_iterator 的 ifstream
char* Data = new char[Size];
File.read(Data, Size);
File.close();
HeaderType *header = reinterpret_cast<HeaderType*>(Data);
/* ... */
delete[] Data;
这是带有 istreambuf_iterator 的 ifstream
std::string Data; // Is it better to use another container type?
Data.reserve(Size);
std::copy((std::istreambuf_iterator<char>(File)), std::istreambuf_iterator<char>(),
std::back_inserter(Data));
File.close();
const HeaderType *header = reinterpret_cast<HeaderType*>(Data.data());
在网上也找到了这个
std::ostringstream Data;
Data << File.rdbuf();
File.close();
std::string String = Data.str();
const HeaderType *header = reinterpret_cast<HeaderType*>(String.data());