读取一个嵌入式文本文件资源Visual Studio c++

Reading an embedded text file resource Visual Studio C++

本文关键字:资源 文件 Visual Studio c++ 文本 嵌入式 一个 读取      更新时间:2023-10-16

将文本文件添加为资源的步骤如下:1. 右键单击项目,添加新项目2. 选择文本文件,单击添加3.转到项目属性,配置属性->链接器->输入->嵌入托管资源文件4. 然后在文本框中添加文本文件items。txt

然后在我的。rc文件中,我放入以下代码:

#include "resource.h"
IDR_DATA1 TEXTFILE "Items.txt"

在resource.h文件中,我放入:

#define TEXTFILE   256
#define IDR_DATA1  255

In my form .cpp method:

std::string result;
char* data = NULL;
HINSTANCE hInst = GetModuleHandle(NULL);
HRSRC hRes = FindResource(hInst, MAKEINTRESOURCE(IDR_DATA1), MAKEINTRESOURCE(TEXTFILE));
if (NULL != hRes)
{
    HGLOBAL hData = LoadResource(hInst, hRes);
    if (hData)
    {
        DWORD dataSize = SizeofResource(hInst, hRes);
        data = (char*)LockResource(hData);
    }
    else
    {
        MessageBox::Show("hData is null");
        return "";
    }
    char* pkcSearchResult = strstr(data, "2000000");
    if (pkcSearchResult != NULL)
        MessageBox::Show(gcnew String(pkcSearchResult));
}
else
    MessageBox::Show("hRes is null");
return result;

我一直得到hRes是null无论什么,出于某种原因FindResource没有找到Items.txt即使我添加了它作为一个资源使用上面的步骤,有人知道为什么FindResource()不工作吗?顺便说一句,它编译没有错误,上面的代码是在一个方法中,应该返回包含"2000000"的文本行(我为测试目的而更改)

看来在上述FindResource函数中交换MAKEINTRESOURCE(IDR_DATA1)MAKEINTRESOURCE(TEXTFILE)的位置是可行的。

它在以下宽字符变化中的操作方式绕过了上面描述的步骤1 - 4,并遵循@In silicon的解决方案:

  • 确保文本文件是ANSI或Unicode取决于要求(UTF-8等需要额外的转换)
  • 将文本文件复制到项目目录
  • 如前所述,分别在项目rc和resource.h中添加以下语句:

    #include "resource.h"
    IDR_DATA1 TEXTFILE "Items.txt"
    

    对于$(ProjectDir)的子目录中的"Items.txt" 用反斜杠转义反斜杠,也可以使用完全限定的路径,但可能不可移植。

    #define TEXTFILE   256
    #define IDR_DATA1  255
    

并定义两个函数:

    void LoadFileInResource(int name, int type, DWORD& size, const wchar_t *& data) // *& is passing the pointer by reference and not by val.
    {
    HMODULE handle = ::GetModuleHandleW(NULL);
    HRSRC rc = ::FindResourceW(handle, MAKEINTRESOURCEW(name), MAKEINTRESOURCEW(type));
    HGLOBAL rcData = ::LoadResource(handle, rc);
    size = ::SizeofResource(handle, rc);
    data = static_cast<const wchar_t*>(::LockResource(rcData));                                                                 
    //LockResource does not actually lock memory; it is just used to obtain a pointer to the memory containing the resource data. 
    }
    wchar_t GetResource()
    {
    DWORD size = 0;
    const wchar_t* data = NULL;
    LoadFileInResource(IDR_MYTEXTFILE, TEXTFILE, size, data);
    /* Access bytes in data - here's a simple example involving text output*/
    // The text stored in the resource might not be NULL terminated.
    wchar_t* buffer = new wchar_t[size + 1];
    ::memcpy(buffer, data, size);
    buffer[size] = 0; // NULL terminator
    delete[] buffer;
    return  *data;
    }

data应该提供上述pkcSearch查询的广泛实现。