From 3304264990b96c09b174716ecb8da63d24457ae8 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Sat, 21 Dec 2019 14:50:03 +0300 Subject: utils/ -> aesxx/utils/ --- aesxx/utils/helpers/file.hpp | 69 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 aesxx/utils/helpers/file.hpp (limited to 'aesxx/utils/helpers/file.hpp') diff --git a/aesxx/utils/helpers/file.hpp b/aesxx/utils/helpers/file.hpp new file mode 100644 index 0000000..48e4c51 --- /dev/null +++ b/aesxx/utils/helpers/file.hpp @@ -0,0 +1,69 @@ +// Copyright (c) 2016 Egor Tensin +// This file is part of the "AES tools" project. +// For details, see https://github.com/egor-tensin/aes-tools. +// Distributed under the MIT License. + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace file +{ + inline std::size_t cast_to_size_t(std::streamoff size) + { + if (size < 0) + throw std::range_error{"file::cast_to_size_t: something went really wrong"}; + typedef std::make_unsigned::type unsigned_streamoff; + if (static_cast(size) > std::numeric_limits::max()) + throw std::range_error{"file::cast_to_size_t: this file is too large"}; + return static_cast(size); + } + + inline std::size_t get_file_size(const std::string& path) + { + std::ifstream ifs; + ifs.exceptions(std::ifstream::badbit | std::ifstream::failbit); + ifs.open(path, std::ifstream::binary | std::ifstream::ate); + return cast_to_size_t(ifs.tellg()); + } + + inline std::vector read_file(const std::string& path) + { + const auto size = get_file_size(path); + + std::ifstream ifs; + ifs.exceptions(std::ifstream::badbit | std::ifstream::failbit); + ifs.open(path, std::ifstream::binary); + + std::vector src_buf; + src_buf.reserve(size); + src_buf.assign( + std::istreambuf_iterator{ifs}, + std::istreambuf_iterator{}); + return src_buf; + } + + inline void write_file( + const std::string& path, + const void* buffer, + const std::size_t size) + { + std::ofstream ofs; + ofs.exceptions(std::ofstream::badbit | std::ofstream::failbit); + ofs.open(path, std::ofstream::binary); + ofs.write(reinterpret_cast(buffer), size); + } + + inline void write_file( + const std::string& path, + const std::vector& src) + { + write_file(path, src.data(), src.size()); + } +} -- cgit v1.2.3