我正在创建一个IOManager类,其中我有一个函数来读取一个文件并将其存储在一个缓冲区中。这样做最有效的方法是什么?
我目前有2段代码:
bool IOManager::readFileToBuffer(std::string filePath, std::vector<unsigned char>& buffer) {
std::ifstream file(filePath, std::ios::binary);
if (file.fail()) {
perror(filePath.c_str());
return false;
}
//seek to the end
file.seekg(0, std::ios::end);
//Get the file size
int fileSize = file.tellg();
file.seekg(0, std::ios::beg);
//Reduce the file size by any header bytes that might be present
fileSize -= file.tellg();
buffer.resize(fileSize);
file.read((char *)&(buffer[0]), fileSize);
file.close();
return true;
}和
bool IOManager::readFileToBuffer(std::string filePath, std::vector<char>& buffer) {
std::ifstream file(filePath, std::ios::binary);
if (file.fail()) {
perror(filePath.c_str());
return false;
}
// copies all data into buffer
std::vector<char> prov(
(std::istreambuf_iterator<char>(file)),
(std::istreambuf_iterator<char>()));
buffer = prov;
file.close();
return true;
}哪一个更好?按照C++11/14标准,这是最快和最有效的方法吗?
发布于 2015-08-25 19:28:52
我希望第一个版本比第二个版本更快。它将是单个流调用,它将转换为单个(除非有信号)内核read()调用。
第二个版本现在有一个潜在的多个重分配的问题,但是这可以通过首先保留大小的向量,而不是从迭代器复制到它来解决。但更大的问题是,它将转换为多个调用来读取()函数。
https://stackoverflow.com/questions/32212255
复制相似问题