1

This a follow up of the question asked and answered here. I want to use a text file as a resource and then load it as a stringstream so that I can parse it.

The following code shows what I currently have:

std::string filename("resource.txt"); HRSRC hrsrc = FindResource(GetModuleHandle(NULL), filename.c_str(), RT_RCDATA); HGLOBAL res = LoadResource(GetModuleHandle(NULL), hrsrc); LPBYTE data = (LPBYTE)LockResource(res); std::stringstream stream((LPSTR)data); 

However, I am unsure of how to extend this to read a unicode text file using a wstringstream. The naive approach yields unreadable characters:

... LPBYTE data = (LPBYTE)LockResource(res); std::wstringstream wstream((LPWSTR)data); 

Since LPBYTE is nothing more than a CHAR*, it is no surprise that this doesn't work, but naively converting the resource to a WCHAR* (LPWSTR) does not work either:

... LPWSTR data = (LPWSTR)LockResource(res); std::wstringstream wstream(data); 

I am guessing this is because a WCHAR is 16-bit instead of 8-bit like a CHAR, but I'm not sure how to work around this.

Thanks for any help!

3
  • 1
    What's the encoding of your resource file? If its ASCII or UTF8, then you need an explicit conversion (like MultiByteToWideChar) to read it as a sequence of unicode characters. Commented Jan 8, 2014 at 15:31
  • Both of your proposed solutions work, as long as resource.txt is in fact UTF-16 encoded. Since you come to the conclusion that "neither one works", it would help if you explained what does not work (what's the expected result and actual result?). Commented Jan 8, 2014 at 16:39
  • My resource.txt file is encoded in UTF-8, so the snippets above give me a string of arbitrary characters. The result I am looking for is to get a wstring of the contents of the file and store that in a wstringstream. Commented Jan 8, 2014 at 17:34

1 Answer 1

2

Your comment supplies the key missing detail. The file that you compiled into a resource is encoded as UTF-8. So the obvious options are:

  1. Using the code in your question, get a pointer to the resource, encoded as UTF-8, and pass that MultiByteToWideChar to convert to UTF-16. Which you can then put into a wstring.
  2. Convert the file that you compile into a resource to UTF-16, before you compile the resource. Then the code in your question will work.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.