SDEngine
Game Engine
Loading...
Searching...
No Matches
file_utils.hpp
Go to the documentation of this file.
1#pragma once
2#include <expected>
3#include <filesystem>
4#include <fstream>
5#include <vector>
6
7#include "SD/core/base.hpp"
8#include "SD/core/types.hpp"
9
10namespace sd {
11
12enum class FileError {
13 NONE,
14 ERROR,
17};
18
24inline std::expected<std::vector<char>, FileError> read_file(const std::string& filename) {
25 std::ifstream file(filename, std::ios::ate | std::ios::binary);
26
27 if (!file.is_open()) {
28 return std::unexpected(FileError::ERROR);
29 }
30
31 const usize file_size = file.tellg();
32 std::vector<char> buffer(file_size);
33
34 file.seekg(0);
35 file.read(buffer.data(), static_cast<std::streamsize>(file_size));
36 file.close();
37
38 if (!file) {
39 return std::unexpected(FileError::ERROR);
40 }
41
42 return buffer;
43}
44
45namespace Filesystem {
51inline FileError read_binary(const std::filesystem::path& path, std::vector<std::byte>& buffer) {
52 std::error_code ec;
53 const auto file_size = std::filesystem::file_size(path, ec);
54 if (ec) {
55 // TODO: handle errors
56 engine_abort(ec.category().name());
57 return FileError::ERROR;
58 }
59 if (file_size == std::numeric_limits<std::uintmax_t>::max()) {
60 // fails to read something
61 return FileError::ERROR;
62 }
63
64 if (file_size > std::numeric_limits<std::size_t>::max()) {
66 }
67
68 buffer.clear();
69 buffer.resize(file_size);
70
71 std::ifstream file(path, std::ios::binary);
72 if (!file)
73 return FileError::ERROR;
74
75 file.read(reinterpret_cast<char*>(buffer.data()), static_cast<std::streamsize>(file_size));
76 if (!file || file.gcount() != static_cast<std::streamsize>(file_size)) {
77 return FileError::ERROR;
78 }
79 return FileError::NONE;
80}
81inline FileError write_binary(const std::filesystem::path& path, const std::vector<std::byte>& data,
82 bool overwrite_existing = false) {
83 if (std::filesystem::exists(path)) {
86 }
87 // truncates by default
88 std::ofstream file(path, std::ios::out | std::ios::binary);
89 file.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
90 // todo: handle error
91 return FileError::NONE;
92}
93} // namespace Filesystem
94
95} // namespace sd
FileError write_binary(const std::filesystem::path &path, const std::vector< std::byte > &data, bool overwrite_existing=false)
Definition file_utils.hpp:81
FileError read_binary(const std::filesystem::path &path, std::vector< std::byte > &buffer)
Definition file_utils.hpp:51
Definition Application.hpp:28
FileError
Definition file_utils.hpp:12
void engine_abort()
Definition base.hpp:46
std::expected< std::vector< char >, FileError > read_file(const std::string &filename)
Definition file_utils.hpp:24
constexpr T g_type_max
Definition types.hpp:21
std::size_t usize
Definition types.hpp:18