Template
70 lines
1.5 KiB
C++
70 lines
1.5 KiB
C++
#include "file-stream.h"
|
|
|
|
#include "core-library/io/io-helper.h"
|
|
|
|
#include <system_error>
|
|
|
|
core::file_stream::~file_stream()
|
|
{
|
|
close();
|
|
}
|
|
|
|
core::file_stream::file_stream(file_stream&& other) noexcept
|
|
: m_file_handle(std::exchange(other.m_file_handle, nullptr))
|
|
{
|
|
}
|
|
|
|
core::file_stream& core::file_stream::operator=(file_stream&& other)
|
|
{
|
|
if (this != &other)
|
|
{
|
|
core::close_file(m_file_handle);
|
|
m_file_handle = std::exchange(other.m_file_handle, nullptr);
|
|
}
|
|
|
|
return *this;
|
|
}
|
|
|
|
core::file_stream core::file_stream::open_for_reading(const std::filesystem::path& file_path)
|
|
{
|
|
file_stream stream{};
|
|
stream.m_file_handle = core::open_file(file_path.string().c_str(), "rb");
|
|
|
|
return stream;
|
|
}
|
|
|
|
std::string core::file_stream::file_content_as_string(const std::filesystem::path& file_path)
|
|
{
|
|
file_stream stream = open_for_reading(file_path);
|
|
return stream.read_all_as_string();
|
|
}
|
|
|
|
std::string core::file_stream::read_all_as_string()
|
|
{
|
|
if (!m_file_handle)
|
|
return {};
|
|
|
|
core::seek_file_to_end(m_file_handle);
|
|
const std::size_t file_size = static_cast<std::size_t>(core::get_file_offset(m_file_handle));
|
|
core::seek_file_to_beginning(m_file_handle);
|
|
|
|
if (file_size == 0)
|
|
return {};
|
|
|
|
std::string result(file_size, '\0');
|
|
core::read_from_file(&result[0], 1, file_size, m_file_handle);
|
|
|
|
return result;
|
|
}
|
|
|
|
void core::file_stream::close()
|
|
{
|
|
if (m_file_handle)
|
|
{
|
|
if (int result = std::fclose(m_file_handle); result != 0)
|
|
throw std::system_error(std::error_code{result, std::system_category()});
|
|
|
|
m_file_handle = nullptr;
|
|
}
|
|
}
|