【发布时间】:2015-03-12 16:52:08
【问题描述】:
我需要读取一个包含标题和数据的二进制文件(一次性)。用 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());
【问题讨论】:
-
当人们将 PascalCase 用于 C++ 变量名时,还有其他人会做双重考虑吗?
标签: c++ ifstream istream-iterator