This commit is contained in:
altalk23 2023-09-14 17:54:32 +03:00
commit 5954b06bc4

View file

@ -21,12 +21,17 @@ using namespace geode::prelude;
using namespace geode::utils::file;
Result<std::string> utils::file::readString(ghc::filesystem::path const& path) {
if (!ghc::filesystem::exists(path))
return Err("File does not exist");
#if _WIN32
std::ifstream in(path.wstring(), std::ios::in | std::ios::binary);
#else
std::ifstream in(path.string(), std::ios::in | std::ios::binary);
#endif
if (in) {
if (!in)
return Err("Unable to open file");
std::string contents;
in.seekg(0, std::ios::end);
contents.resize((const size_t)in.tellg());
@ -35,34 +40,32 @@ Result<std::string> utils::file::readString(ghc::filesystem::path const& path) {
in.close();
return Ok(contents);
}
return Err("Unable to open file");
}
Result<json::Value> utils::file::readJson(ghc::filesystem::path const& path) {
auto str = utils::file::readString(path);
if (str) {
if (!str)
return Err(str.unwrapErr());
try {
return Ok(json::parse(str.value()));
} catch(std::exception const& e) {
return Err("Unable to parse JSON: " + std::string(e.what()));
}
} else {
return Err("Unable to open file");
catch(std::exception const& e) {
return Err("Unable to parse JSON: " + std::string(e.what()));
}
}
Result<ByteVector> utils::file::readBinary(ghc::filesystem::path const& path) {
if (!ghc::filesystem::exists(path))
return Err("File does not exist");
#if _WIN32
std::ifstream in(path.wstring(), std::ios::in | std::ios::binary);
#else
std::ifstream in(path.string(), std::ios::in | std::ios::binary);
#endif
if (in) {
return Ok(ByteVector(std::istreambuf_iterator<char>(in), {}));
}
if (!in)
return Err("Unable to open file");
return Ok(ByteVector(std::istreambuf_iterator<char>(in), {}));
}
Result<> utils::file::writeString(ghc::filesystem::path const& path, std::string const& data) {
@ -72,16 +75,16 @@ Result<> utils::file::writeString(ghc::filesystem::path const& path, std::string
#else
file.open(path.string());
#endif
if (file.is_open()) {
file << data;
file.close();
return Ok();
}
if (!file.is_open()) {
file.close();
return Err("Unable to open file");
}
file << data;
file.close();
return Ok();
}
Result<> utils::file::writeBinary(ghc::filesystem::path const& path, ByteVector const& data) {
std::ofstream file;
#if _WIN32
@ -89,16 +92,16 @@ Result<> utils::file::writeBinary(ghc::filesystem::path const& path, ByteVector
#else
file.open(path.string(), std::ios::out | std::ios::binary);
#endif
if (file.is_open()) {
file.write(reinterpret_cast<char const*>(data.data()), data.size());
file.close();
return Ok();
}
if (!file.is_open()) {
file.close();
return Err("Unable to open file");
}
file.write(reinterpret_cast<char const*>(data.data()), data.size());
file.close();
return Ok();
}
Result<> utils::file::createDirectory(ghc::filesystem::path const& path) {
try {
#ifdef GEODE_IS_WINDOWS