在exe中包含文本文件作为本地资源

时间:2012-11-15 23:54:00

标签: visual-studio-2010 visual-c++ mfc

我有一个文本文件,我想包含在一个独立的可执行文件中。文件本身位于另一个目录的源代码控制中,我想我希望在编译时将文本文件添加到可执行文件中。

我一直在阅读有关资源的内容,但我不确定添加文件的最佳方法是什么。我也不知道在执行过程中如何引用和读取文件。

该项目是静态链接的MFC,我正在使用vs2010。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:5)

只需将文件作为资源添加到您的应用程序中。您可以使用与此类似的代码“读取”它:

/* the ID is whatever ID you choose to give the resource. The "type" is
 * also something you choose. It will most likely be something like "TEXTFILE"
 * or somesuch. But anything works.
 */
HRSRC hRes = FindResource(NULL, <ID of your resource>, _T("<type>")); 
HGLOBAL hGlobal = NULL;
DWORD dwTextSize = 0;

if(hRes != NULL)
{
    /* Load the resource */
    hGlobal = LoadResource(NULL, hRes);

    /* Get the size of the resource in bytes (i.e. the size of the text file) */
    dwTextSize = SizeofResource(NULL, hRes);
}

if(hGlobal != NULL)
{ 
    /* I use const char* since I assume that your text file is saved as ASCII. If
     * it is saved as UNICODE adjust to use const WCHAR* instead but remember 
     * that dwTextSize is the size of the memory buffer _in bytes_).
     */
    const char *lpszText = (const char *)LockResource(hGlobal);

    /* at this point, lpszText points to a block of memory from which you can
     * read dwTextSize bytes of data. You *CANNOT* modify this memory.
     */
    ... whatever ...
}