4

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

我一直在阅读一些有关资源的信息,但我不确定添加文件的最佳方法是什么。我也不知道在执行期间如何引用和读取文件。

该项目是静态链接的MFC,我使用的是vs2010。任何帮助将非常感激。

4

1 回答 1

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 ...
}
于 2012-11-16T05:29:25.443 回答