Loading files from resources

Started by _Mir_.cpp, 17 April 2025, 18:45:21

_Mir_.cpp

I found a workaround to use resources from .exe file on Windows (Microsoft VC++): I used temporary files. We need to add our files to resource.rc and use this code:
At the beginning of the program:
#include <fstream> // To save files
#include <stdio.h> // To delete files

// Define some types and functions because if we use Windows.h, an error appears: you cannot override the WinMain() function.
using DWORD = uint32_t;
using LPVOID = void*;
typedef void* HINSTANCE;
typedef wchar_t WCHAR;
typedef const char* LPCSTR;
typedef const WCHAR* LPWCSTR;
typedef unsigned int UINT;
typedef void* HGLOBAL;
typedef void* HRSRC;
typedef void* HMODULE;
extern "C" {
HRSRC FindResourceA(HMODULE hModule, LPCSTR lpName, LPCSTR lpType);
HRSRC FindResourceW(HMODULE hModule, LPWCSTR lpName, LPWCSTR lpType);
HGLOBAL LoadResource(HMODULE hModule, HRSRC hResInfo);
void* LockResource(HGLOBAL hResData);
unsigned int SizeofResource(HMODULE hModule, HRSRC hResInfo);
}

This is my function to save temporary files:
bool SaveResourceToFile(const WCHAR* resourceName, const WCHAR* resourceType, const WCHAR* outputFilePath)
{
// Find a resource
HRSRC hResource = FindResourceW(NULL, resourceName, resourceType);
if (hResource == NULL) {
return false;
}

// Load a resource
HGLOBAL hMemory = LoadResource(NULL, hResource);
if (hMemory == NULL) {
return false;
}

// Get resource size
DWORD resourceSize = SizeofResource(NULL, hResource);
if (resourceSize == 0) {
return false;
}

// Get a pointer to the resource data
LPVOID resourceData = LockResource(hMemory);
if (resourceData == NULL) {
return false;
}

// Write data to file
std::ofstream outputFile(outputFilePath, std::ios::binary);
if (!outputFile.is_open()) {
return false;
}

outputFile.write(static_cast<const char*>(resourceData), resourceSize);
outputFile.close();

return true;
}

Now we can do this:
SaveResourceToFile(L"#101",L"PNG",L"TempFileScannerIcon.png"); // Saving files
SaveResourceToFile(L"#103",L"TXT",L"TempFileScannerWidgetsList.txt");
// ...
// Using our files
// ...
remove("TempFileScannerIcon.png"); // Removing files
remove("TempFileScannerWidgetsList.txt");

Note that I had some problems with resources with default type (like "Icon"), but may be I did something wrong.