From 31cd55cf1fab8f08f8be662fa8b4172664dd4e78 Mon Sep 17 00:00:00 2001 From: Kevin Trogant Date: Thu, 8 Dec 2022 11:51:03 +0100 Subject: [PATCH] WriteFile function - Basic version takes buffer + size - For convenience: version that takes a FileBuffer --- app/src/main/cpp/Win32AssetManager.cpp | 41 +++++++++++++++++++++++++- app/src/main/cpp/Win32AssetManager.h | 13 ++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/app/src/main/cpp/Win32AssetManager.cpp b/app/src/main/cpp/Win32AssetManager.cpp index 1a06715..4f2651e 100644 --- a/app/src/main/cpp/Win32AssetManager.cpp +++ b/app/src/main/cpp/Win32AssetManager.cpp @@ -66,4 +66,43 @@ void Win32AssetManager::releaseFileBuffer(FileBuffer& fb) VirtualFree(data, 0, MEM_RELEASE); fb.data = nullptr; fb.size = 0; -} \ No newline at end of file +} + +bool Win32AssetManager::writeFile(const char* path, const void* data, size_t size) +{ + char _cp[MAX_PATH]; + strncpy(_cp, m_asset_root, MAX_PATH); + strncat(_cp, "\\", MAX_PATH); + strncat(_cp, path, MAX_PATH); + + HANDLE file = + CreateFileA(_cp, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, INVALID_HANDLE_VALUE); + if (!file) { + return false; + } + + const char* at = reinterpret_cast(data); + while (size >= UINT32_MAX) { + DWORD bytes_written = 0; + if (!WriteFile(file, at, UINT32_MAX, &bytes_written, nullptr)) { + CloseHandle(file); + return false; + } + size -= bytes_written; + at += bytes_written; + } + if (size > 0) { + DWORD bytes_written = 0; + if (!WriteFile(file, at, size, &bytes_written, nullptr)) { + CloseHandle(file); + return false; + } + } + CloseHandle(file); + return true; +} + +bool Win32AssetManager::writeFile(const char* path, const FileBuffer& file_buffer) +{ + return writeFile(path, file_buffer.data, file_buffer.size); +} diff --git a/app/src/main/cpp/Win32AssetManager.h b/app/src/main/cpp/Win32AssetManager.h index b9b62df..c406d41 100644 --- a/app/src/main/cpp/Win32AssetManager.h +++ b/app/src/main/cpp/Win32AssetManager.h @@ -16,6 +16,19 @@ public: void releaseFileBuffer(FileBuffer& fb) override; + /// @brief Write data to a file. + /// @param path Path relative to the asset root directory + /// @param data Data buffer + /// @param size Number of bytes + /// @return @c true if writing the file was successfull, @c false otherwise + bool writeFile(const char* path, const void* data, size_t size); + + /// @brief Write data to a file. + /// @param path Path relative to the asset root directory + /// @param file_buffer Data buffer + /// @return @c true if writing the file was successfull, @c false otherwise + bool writeFile(const char* path, const FileBuffer& file_buffer); + private: const char* m_asset_root; };