Include text file as local resource in exe

I have a text file that I would like to include in a standalone executable. The file itself is located in the source control in a different directory, and I think I want the text file to be added to the executable at compile time.

I read a little about resources, but I don’t know exactly what would be the best way to add a file. I also do not know how I will reference and read from a file at runtime.

The project is statically linked to MFC, and I am using vs2010. Any help would be greatly appreciated.

+4
source share
1 answer

Just add the file as a resource to your application. You can "read" it with code like this:

/* 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 (ie 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 ... } 
+5
source

Source: https://habr.com/ru/post/1446353/


All Articles