i am working on a win32 app. i am currently using the text file which has tab delimited data as a source. i want to embed this as a resource so that i need not worry about shipping 开发者_如何学Cthis file along with .exe file.
can anyone tell me how to do it?
Windows binary can have resources embedded in them. Most resources are of predetermined type (e.g. a menu, an icon or a bitmap) but you can also embed arbitrary binary data (e.g. a text file). The proper syntax is hard to figure out just from reading msdn docs.
This snippet shows how to embed a binary resource from a file.
First you need to define a resource identifier in a header file (e.g. resource.h) that will be used by both C compiler and resource compiler:
#define MY_RESOURCE 300
Then you need to add to your resource file (e.g. resource.rc):
MY_RESOURCE RCDATA "file-with-data.txt"
And finally, this is how you can get to this data:
void WorkOnResource(void) { HGLOBAL res_handle = NULL; HRSRC res; char * res_data; DWORD res_size; // NOTE: providing g_hInstance is important, NULL might not work res = FindResource(g_hInstance, MAKEINTRESOURCE(MY_RESOURCE), RT_RCDATA); if (!res) return; res_handle = LoadResource(NULL, res); if (!res_handle) return; res_data = (char*)LockResource(res_handle); res_size = SizeofResource(NULL, res); /* you can now use the resource data */ }
Define the resource ID, add this to the .rc file:
ID_CUSTOM1 ANYTHINGGOESHERE "filename.txt"
Read it at runtime with code like this:
HRSRC hRes = FindResource(hInst, MAKEINTRESOURCE(ID_CUSTOM1), L"ANYTHINGGOESHERE");
HGLOBAL hMem = LoadResource(hInst, hRes);
DWORD size = SizeofResource(hInst, hRes);
char* resText = (char*)LockResource(hMem);
char* text = (char*)malloc(size + 1);
memcpy(text, resText, size);
text[size] = 0;
FreeResource(hMem);
// use text...
why not use a header file and put all your data in a static array. That way you don't have to parse a text file or worry about deployment
If you are looking for the "correct" way to do this then I would suggest adding your text file as a resource (as a string table or binary) and using LoadString or FindResource to access it.
in Visual Studio, you can add text as a resource just like any other resource.
In the resource.rc file of your project:
IDR_MYRESOURCE MYCUSTOMRESOURCETYPE "path_to_file.txt"
in the resource.h file:
#define IDR_MYRESOURCE 104
(or you can add these through the resource editor by selecting "Add Resource", then "New")
To load the resource in code:
HRSRC hRes = FindResource( 0, "#104", "MYCUSTOMRESOURCETYPE" );
HGLOBAL hData = LoadResource( 0, hRes );
LPVOID data = LockResource( hData );
Now data points to the text, and can be casted to string.
edit hmm looks like everyone was posting the same answer at the same time ;P
精彩评论