Question

This code below doesn't work correctly since my MFC program is in unicode circumstance.

::WriteFile(hFile, TEXT("123456"), lstrlenW(TEXT("123456")), &dwByte, nullptr);
::CloseHandle(hFile);

The result is "123", which is supposed to be "123456"

I found on the internet that Unicode BOM could solve this. So I modified my code to go like this below.

WORD Unicode = 0xfeff; // UNICODE BOM
::WriteFile(hFile, &Unicode, 2, &dwByte, nullptr);
::WriteFile(hFile, TEXT("123456"), lstrlenW(TEXT("123456")), &dwByte, nullptr);
::CloseHandle(hFile);

However, it doesn't make any difference.

Seems like it's a simple problem but I am lost looking for the solution to this.

Any idea would be more than welcomed. Thanks in advance.

Was it helpful?

Solution

Writefile does not write "text": it write "Bytes". The lstrlenW returns the number of wchar_t. You shold multiply by sizeof(wchar_t) in order to give to the third parameter the "number of bytes to write"

OTHER TIPS

You don't want to use lstrlenW to determine the amount of data to write -- you need to tell WriteFile the number of bytes to write, not the number of code points. Right now, you're telling it 6, which is enough bytes for 3 characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top