How to load text file from Resources in VC++?

拟墨画扇 提交于 2019-12-18 11:56:10

问题


I'm writing a DLL in VC++ and I need to use external text file. I have something like this right now:

 ifstream file;
 string line;

 file.open("C:\\Users\\Me\\Desktop\\textfile.txt");
 getline(file,line);
 file.close();

I understand that I can have this file in Resources right?

I added my text file by going to "ResourceView" -> "Add Resource" -> "Import". I chose my text file and created custom resource type.

How can I access to this file to use similarly to the code above ? I have Resource.h but what should I do with it? Can I edit my resource text file too?


回答1:


Assumptions:

  • The resource type is "TEXT"
  • The resource ID is MY_RESOURCE_ID (this would be a constant from your resource.h)
  • You have stored the hInstance for your EXE or DLL (whichever contains the resource) into m_hInstance.

Loading a resource into memory and getting a pointer to it is done like this:

HRSRC hResource = FindResource(m_hInstance, MAKEINTRESOURCE(MY_RESOURCE_ID), L"TEXT");

if (hResource)
{
    HGLOBAL hLoadedResource = LoadResource(m_hInstance, hResource);

    if (hLoadedResource)
    {
        LPVOID pLockedResource = LockResource(hLoadedResource);

        if (pLockedResource)
        {
            DWORD dwResourceSize = SizeofResource(m_hInstance, hResource);

            if (0 != dwResourceSize)
            {
                 // Use pLockedResource and dwResourceSize however you want
            }
        }
    }
}

Note: You do not have to unload or unlock the resource on 32-bit or 64-bit vesions of Windows, and if you obtain the resource again you will not leak memory; you always get the same piece of memory.

For updating a resource, see Updating Resources in MSDN.



来源:https://stackoverflow.com/questions/4344486/how-to-load-text-file-from-resources-in-vc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!