diff --git a/src/EterPack/Folder.cpp b/src/EterPack/Folder.cpp index 906f8a14..d7ec3a37 100644 --- a/src/EterPack/Folder.cpp +++ b/src/EterPack/Folder.cpp @@ -76,23 +76,32 @@ bool Folder::fileExists(const std::string& fileName) bool Folder::getFile(const std::string& fileName, std::shared_ptr>& fileData) { - std::string realFileName = fileName; - std::string ymirPrefix = "d:/"; + constexpr char ymirPrefix[] = "d:/"; + std::string relative = fileName; + if (relative.rfind(ymirPrefix, 0) == 0) + relative.erase(0, sizeof(ymirPrefix) - 1); - if (fileName.find(ymirPrefix) == 0) - realFileName = realFileName.substr(ymirPrefix.length()); + std::filesystem::path p = folderPath; + p /= relative; - realFileName = this->folderPath + "/" + realFileName; - - // Try to open the file - std::ifstream file(realFileName, std::ios::binary); + std::ifstream file(p, std::ios::binary | std::ios::ate); if (!file.is_open()) return false; - // Read the file's contents - fileData = std::make_shared>( - std::istreambuf_iterator(file), - std::istreambuf_iterator() - ); + // get size in one call + std::ifstream::pos_type sz = file.tellg(); + if (sz < 0) + return false; + + // allocate exactly once + auto buf = std::make_shared>(static_cast(sz)); + + // rewind and read in one go + file.seekg(0, std::ios::beg); + file.read(buf->data(), sz); + if (!file) + return false; + + fileData = std::move(buf); return true; } \ No newline at end of file