galaxy 1.0.0
Real-Time C++23 Game Programming Framework. Built on data-driven design principles and agile software engineering.
Loading...
Searching...
No Matches
FileUtils.cpp
Go to the documentation of this file.
1
7
8#include <fstream>
9
10#include "FileUtils.hpp"
11
12namespace galaxy
13{
14 namespace fileutils
15 {
16 std::optional<std::string> extension(const std::string& filepath) noexcept
17 {
18 const auto path = std::filesystem::path(filepath);
19 if (path.has_extension())
20 {
21 return std::make_optional(path.extension().string());
22 }
23
24 return std::nullopt;
25 }
26
27 std::expected<std::string, FileError> read(const std::string& filepath)
28 {
29 const auto path = std::filesystem::path(filepath);
30 if (!std::filesystem::exists(path))
31 {
32 return std::unexpected(FileError("read", "File does not exist.", path));
33 }
34
35 if (!std::filesystem::is_regular_file(path))
36 {
37 return std::unexpected(FileError("read", "Path is an irregular file or a directory", path));
38 }
39
40 std::ifstream input {path, std::ifstream::in};
41 if (!input.good())
42 {
43 return std::unexpected(FileError("read", "Permission denied.", path));
44 }
45
46 std::string buffer(std::filesystem::file_size(path), '\0');
47 input.read(buffer.data(), buffer.size());
48 if (!input.good())
49 {
50 return std::unexpected(FileError("read", "Failed to read file.", path));
51 }
52
53 return buffer;
54 }
55
56 std::optional<FileError> write(const std::string& filepath, const std::string& data)
57 {
58 const auto path = std::filesystem::path(filepath);
59 if (std::filesystem::exists(path))
60 {
61 if (std::filesystem::is_directory(path))
62 {
63 return std::make_optional(FileError("write", "Tried to write to a directory not a file.", path));
64 }
65 }
66
67 std::ofstream ofs {path, std::ofstream::out | std::ofstream::trunc};
68 if (!ofs.good())
69 {
70 return std::make_optional(FileError("write", "Permission denied.", path));
71 }
72
73 ofs << data;
74
75 if (ofs.fail())
76 {
77 return std::make_optional(FileError("write", "Failed to write into file.", path));
78 }
79
80 return std::nullopt;
81 }
82 } // namespace fileutils
83} // namespace galaxy
Stores information about a File I/O error.
Definition FileError.hpp:20
std::optional< FileError > write(const std::string &filepath, const std::string &data)
Writes a non-binary file to disk.
Definition FileUtils.cpp:56
std::optional< std::string > extension(const std::string &filepath) noexcept
Get a file or path's extension.
Definition FileUtils.cpp:16
std::expected< std::string, FileError > read(const std::string &filepath)
Read a non-binary file on disk.
Definition FileUtils.cpp:27
Timer.hpp galaxy.
Definition Timer.cpp:18