VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
File.cpp
Go to the documentation of this file.
3#include <filesystem>
4#include <format>
5#include <fstream>
6#include <iterator>
7#include <system_error>
8
9namespace VoltMod
10{
11
12Result<std::string> ReadAllText(std::string_view path)
13{
14 const auto resolved = ResolvePath(path);
15 std::ifstream file(resolved, std::ios::binary);
16 if (!file.is_open())
17 {
18 return std::unexpected(Error::NotFound(std::format("failed to open {}", resolved.string())));
19 }
20
21 return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
22}
23
24Status WriteAllText(std::string_view path, std::string_view text)
25{
26 const auto resolved = ResolvePath(path);
27 std::error_code ignored;
28 std::filesystem::create_directories(resolved.parent_path(), ignored);
29
30 std::ofstream file(resolved, std::ios::binary | std::ios::trunc);
31 if (!file.is_open())
32 {
33 return std::unexpected(Error::Invalid(std::format("failed to open {}", resolved.string())));
34 }
35
36 file.write(text.data(), static_cast<std::streamsize>(text.size()));
37 if (!file)
38 {
39 return std::unexpected(Error::Invalid(std::format("failed to write {}", resolved.string())));
40 }
41 return {};
42}
43
44} // namespace VoltMod
std::filesystem::path ResolvePath(std::string_view relativePath)
a relative path against the base directory. If the path is already absolute, returns it as-is.
Definition Paths.cpp:14
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56
Result< std::string > ReadAllText(std::string_view path)
Read path (resolved via ResolvePath) into a string.
Definition File.cpp:12
std::expected< void, Error > Status
Definition Result.hpp:67
Status WriteAllText(std::string_view path, std::string_view text)
Write text to path (resolved via ResolvePath), creating its directory.
Definition File.cpp:24
std::expected< T, Error > Result
Definition Result.hpp:64
static Error Invalid(std::string detail)
Definition Result.hpp:51
static Error NotFound(std::string detail)
Definition Result.hpp:49