/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" #include "utilities/wholefile.h" #include whole_file read_whole_file(std::string const &Path) { whole_file result; auto *const file{std::fopen(Path.c_str(), "rb")}; if (file == nullptr) { return result; } // without a buffer of its own the stream hands the read to the system in one piece, straight into the memory std::setvbuf(file, nullptr, _IONBF, 0); #ifdef _WIN32 _fseeki64(file, 0, SEEK_END); auto const length{_ftelli64(file)}; _fseeki64(file, 0, SEEK_SET); #else fseeko(file, 0, SEEK_END); auto const length{ftello(file)}; fseeko(file, 0, SEEK_SET); #endif if (length > 0) { result.data.reset(new char[static_cast(length)]); result.size = std::fread(result.data.get(), 1, static_cast(length), file); } std::fclose(file); return result; } namespace { bool seek_to(std::FILE *const File, std::uint64_t const Offset, int const Origin) { #ifdef _WIN32 return _fseeki64(File, static_cast<__int64>(Offset), Origin) == 0; #else return fseeko(File, static_cast(Offset), Origin) == 0; #endif } } // namespace file_parts::file_parts(std::string const &Path) { m_file = std::fopen(Path.c_str(), "rb"); if (m_file == nullptr) { return; } std::setvbuf(m_file, nullptr, _IONBF, 0); seek_to(m_file, 0, SEEK_END); #ifdef _WIN32 auto const length{_ftelli64(m_file)}; #else auto const length{ftello(m_file)}; #endif m_size = (length > 0 ? static_cast(length) : 0); } file_parts::~file_parts() { if (m_file != nullptr) { std::fclose(m_file); } } bool file_parts::read(std::uint64_t const Offset, std::size_t const Size, void *const Output) { if ((m_file == nullptr) || (Offset > m_size) || (Size > m_size - Offset)) { return false; } if (Size == 0) { return true; } return seek_to(m_file, Offset, SEEK_SET) && (std::fread(Output, 1, Size, m_file) == Size); }