Click here to Skip to main content
15,867,851 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have the following. It shows up correctly in Microsoft NotePad. It does not show up correctly in Microsoft Wordpad.

Using CodeBlocks 17.12 / MinGW with GCC 5.1 / 32 bit Microsoft Windows XP Pro sp2.

__________

When I open the txt file with Microsoft WordPad I get :
h e l l o - J s0"0k0a0o0 - a b c d e f g h i j k l m n o p q r s t u v w x y

WRONG and Not usable.

__________

When I open the txt file with Microsoft Notepad I get :
hello - J - こんにちは - abcdefghijklmnopqrstuvwxy

RIGHT and Usable.

My code:

What I have tried:

HANDLE hDFile = CreateFile(L"utf8_UsingByteOrderMark_C_天堂.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

DWORD NumberOfBytesWritten;

BOOL bErr = 0;

unsigned char BOM[3]{ 0xef, 0xbb, 0xbf };

bErr = WriteFile(hFile, (LPCVOID)BOM, (DWORD)sizeof(BOM), &dwBytesWritten, NULL);

bErr = WriteFile(hDFile, L"hello - J - こんにちは - abcdefghijklmnopqrstuvwxyz", 90, &NumberOfBytesWritten, NULL);

CloseHandle(hDFile);
Posted
Updated 9-Aug-22 4:55am
v2
Comments
Richard MacCutchan 9-Aug-22 11:47am    
You have added a UTF8 BOM to your file, but then you have written Unicode (16 bit) characters to it. The correct BOM for Unicode text is 0xFF 0xFE.

1 solution

The code should work, however your code has issues and errors (dwBytesWritten and hFile are undefined). Here is the fixed code.

HANDLE hDFile = CreateFile(L"utf8_UsingByteOrderMark_C_天堂.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

DWORD NumberOfBytesWritten;

BOOL bErr = 0;

DWORD dwBytesWritten;

unsigned char BOM[3]{ 0xef, 0xbb, 0xbf };

bErr = WriteFile(hDFile, (LPCVOID)BOM, (DWORD)sizeof(BOM), &dwBytesWritten, NULL);

bErr = WriteFile(hDFile, L"hello - J - こんにちは - abcdefghijklmnopqrstuvwxyz", 90, &NumberOfBytesWritten, NULL);

CloseHandle(hDFile);
 
Share this answer
 
Comments
Member 15078716 16-Sep-22 5:15am    
For your answer:
WordPad showed "h" and that is all.
NotePad game me a bunch of ascii characters for the こんにちは.
You tried, rather than telling me how stupid I am, so I accepted your answer.

It is ok. You tried.

Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900