I'm creating a IOManager class in which I have a function to read a file and store it in a buffer. What is the most efficient way of doing that?
I currently have 2 pieces of code:
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;
}
and
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;
}
Which one is better? Is this the fastest and most efficient way of doing this according to the C++11/14 standards?