skip to Main Content

I am on Visual Studio 2022, and I have a project built with a C++ code.
The code looks for a data file "C:/MyData/data.dat", and the absolute path "C:/MyData/data.dat" is written in the .cpp source code.

I would like to incorporate the file data.dat into the .exe file (to make it self-contained and portable) and tell the exe file to look for data.dat ‘inside itself’. How may I do this? With what should I replace "C:/MyData/data.dat" in the .cpp file.

Thank you

2

Answers


  1. You have a) to add the resource in a .RC file, for example

    FILE DATA "c:\file.dat"
    

    and b) to Load it at runtime with FindResource and LoadResource and LockResource and SizeOfResource.

    auto h1 = FindResource(GetModuleHandle(nullptr),L"FILE",L"DATA");
    auto h2 = LoadResource(GetModuleHandle(nullptr),h1);
    void* ptr = LockResource(h2);
    auto sz = SizeOfResource(GetModuleHandle(nullptr),h2);
    // ....
    // use ptr. No free needed.
    
    Login or Signup to reply.
  2. You should be able to read the embedded file using io.
    E.g.
    Convert void* to char*

    main.cpp

    #include <iostream>
    #include<Windows.h>
    #include<Libloaderapi.h>
    #include"resource.h"
    
    int main()
    {
        HRSRC hResource = FindResource(GetModuleHandle(nullptr), MAKEINTRESOURCE(IDR_FILE_DATA),  L"DATA");
        if (hResource == nullptr) {
           
            return -1;
        }
        HGLOBAL hGlobal = LoadResource(GetModuleHandle(nullptr), hResource);
        if (hGlobal == nullptr) {
           
            return -1;
        }
        void* pData = LockResource(hGlobal);
        auto sz = SizeofResource(GetModuleHandle(nullptr), hResource);
        std::cout << (char*)pData; 
    }
    

    resource.h

    #define IDR_FILE_DATA       102
    

    resource.rc

    IDR_FILE_DATA                    DATA         "C://MyData//data.dat" 
    

    enter code here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search