I was trying to make a very basic text editor with Win32 that has the ability to read files and change the text of an edit control to it. I want it to be able to handle chars in all languages, so I tried to use a LPWSTR
for the second parameter of ReadFile()
, like this:
HANDLE file = CreateFile(_T("D:\\C++ Stuff\\Testing.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD fileSize = GetFileSize(file, NULL);
LPWSTR buffer = (LPWSTR)GlobalAlloc(GPTR, fileSize + 1);
DWORD read;
ReadFile(file, buffer, fileSize, &read, NULL);
MessageBox(NULL, buffer, NULL, NULL);
GlobalFree(buffer);
But the MessageBox shows up with a bunch of gibberish! If I use debug mode and add a watch to buffer
, it's still the same. It makes no difference if the file opening contains UTF-16 encoded chars or not. Is this normal? If yes, is there any alternative way to read the file into a LPWSTR
? If no, how to fix it?
I'm using Visual Studio 2015 for this project.
P.S. The code provided is only an example. In the actual code, I have checks for if CreateFile()
, GetFileSize()
, GlobalAlloc()
and ReadFile()
failed or not and null-termination of buffer
.