最近,我被要求编写一个函数,将二进制文件读入 std::vector<BYTE>,其中 BYTE是 unsigned char。我很快就想到了这样的东西:
#include <fstream>
#include <vector>
typedef unsigned char BYTE;
std::vector<BYTE> readFile(const char* filename)
{
// open the file:
std::streampos fileSize;
std::ifstream file(filename, std::ios::binary);
// get its size:
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// read the data:
std::vector<BYTE> fileData(fileSize);
file.read((char*) &fileData[0], fileSize);
return fileData;
}
这似乎是不必要的复杂和明确的转换到 char*,我被迫使用时,呼叫 file.read并没有让我感觉更好。
另一种选择是使用 std::istreambuf_iterator:
std::vector<BYTE> readFile(const char* filename)
{
// open the file:
std::ifstream file(filename, std::ios::binary);
// read the data:
return std::vector<BYTE>((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
}
这是相当简单和短,但仍然我必须使用的 std::istreambuf_iterator<char>,甚至当我读入 std::vector<unsigned char>。
最后一个看起来非常简单的选项是使用 std::basic_ifstream<BYTE>,它明确地表达了 “我想要一个输入文件流,我想用它来读取 BYTE”:
std::vector<BYTE> readFile(const char* filename)
{
// open the file:
std::basic_ifstream<BYTE> file(filename, std::ios::binary);
// read the data:
return std::vector<BYTE>((std::istreambuf_iterator<BYTE>(file)),
std::istreambuf_iterator<BYTE>());
}
但我不确定 basic_ifstream在这种情况下是否是一个合适的选择。
将二进制文件读入 vector的最佳方法是什么?我还想知道 “幕后黑手”发生了什么,以及我可能遇到的问题是什么(除了流没有被正确打开,这可以通过简单的 is_open检查来避免)。
在这里使用 std::istreambuf_iterator有什么好的理由吗?
(我能看到的唯一优势就是简单)