From bd164d2735650a315e07fd633d37701fa4983405 Mon Sep 17 00:00:00 2001 From: Connor McLaughlin <stenzek@gmail.com> Date: Thu, 18 Jun 2020 21:26:22 +1000 Subject: [PATCH] Common/FileSystem: Add {Read,Write}BinaryFile helpers --- src/common/file_system.cpp | 31 +++++++++++++++++++++++++++++++ src/common/file_system.h | 4 ++++ 2 files changed, 35 insertions(+) diff --git a/src/common/file_system.cpp b/src/common/file_system.cpp index b7b85bb1a..ecdb9a90b 100644 --- a/src/common/file_system.cpp +++ b/src/common/file_system.cpp @@ -401,6 +401,37 @@ std::FILE* OpenCFile(const char* filename, const char* mode) #endif } +std::optional<std::vector<u8>> ReadBinaryFile(const char* filename) +{ + ManagedCFilePtr fp = OpenManagedCFile(filename, "rb"); + if (!fp) + return std::nullopt; + + std::fseek(fp.get(), 0, SEEK_END); + long size = std::ftell(fp.get()); + std::fseek(fp.get(), 0, SEEK_SET); + if (size < 0) + return std::nullopt; + + std::vector<u8> res(static_cast<size_t>(size)); + if (size > 0 && std::fread(res.data(), 1u, static_cast<size_t>(size), fp.get()) != static_cast<size_t>(size)) + return std::nullopt; + + return res; +} + +bool WriteBinaryFile(const char* filename, const void* data, size_t data_length) +{ + ManagedCFilePtr fp = OpenManagedCFile(filename, "wb"); + if (!fp) + return false; + + if (data_length > 0 && std::fwrite(data, 1u, data_length, fp.get()) != data_length) + return false; + + return true; +} + void BuildOSPath(char* Destination, u32 cbDestination, const char* Path) { u32 i; diff --git a/src/common/file_system.h b/src/common/file_system.h index bb972e272..a2202f290 100644 --- a/src/common/file_system.h +++ b/src/common/file_system.h @@ -3,6 +3,7 @@ #include "types.h" #include <cstdio> #include <memory> +#include <optional> #include <string> #include <vector> @@ -168,6 +169,9 @@ using ManagedCFilePtr = std::unique_ptr<std::FILE, void (*)(std::FILE*)>; ManagedCFilePtr OpenManagedCFile(const char* filename, const char* mode); std::FILE* OpenCFile(const char* filename, const char* mode); +std::optional<std::vector<u8>> ReadBinaryFile(const char* filename); +bool WriteBinaryFile(const char* filename, const void* data, size_t data_length); + // creates a directory in the local filesystem // if the directory already exists, the return value will be true. // if Recursive is specified, all parent directories will be created