C ++ text file is not saved in Unicode, it saves saving in ANSI

Basically, I need to be able to create a text file in Unicode, but whatever I do, it saves the save in ANSI.

Here is my code:

    wchar_t name[] = L"‎中國哲學書電子化計劃";
    FILE * pFile;
    pFile = fopen("chineseLetters.txt", "w");

    fwrite(name, sizeof(wchar_t), sizeof(name), pFile);
    fclose(pFile);

And here is the output of my "chineseLetters.txt":

     -NWòTx[øfû–P[SŠƒR  õ2123

In addition, the application is located in MBCS and cannot be modified in Unicode, since it must work with both Unicode and ANSI.

I would really appreciate help here. Thank.

Thanks for all the quick answers! He works!

Just adding L "\ uFFFE 中國 哲學 書 電子 化 計劃" still does not work, the text editor still recognized it as CP1252, so I made 2 fwrite instead of one, one for specification and one for characters, here is my code now:

    wchar_t name[] = L"‎中國哲學書電子化計劃";
    unsigned char bom[] = { 0xFF, 0xFE };
    FILE * pFile;
    pFile = fopen("chineseLetters.txt", "w");
    fwrite(bom, sizeof(unsigned char), sizeof(bom), pFile);
    fwrite(name, sizeof(wchar_t), wcslen(name), pFile);
    fclose(pFile);
+4
2

Unicode

Unicode , UTF-16LE? , Windows x86/x64 , Windows, Notepad, UTF-16LE "Unicode" .

fwrite (, sizeof (wchar_t), sizeof (), pFile);

. Windows/MSVCRT, , - UTF-16LE, , , UTF-16LE. , .

"chineseLetters.txt": -NWòTx [øfû-P [SŠƒR õ2123

, UTF-16LE , Windows Code 1252 ().

Windows, "", , , , UTF-16LE, (ANSI, mbcs) , mojibake.

UTF-16, U + FEFF , , UTF-16LE UTF-16BE. , Notepad, , UTF-16 , ANSI. , , , , L"\uFEFF‎中國哲學書電子化計劃" "".

, , wchar_t char , (, UTF-8), , , C. Win32 WideCharToMultibyte API ccs, Mr.C64. UTF-16LE ccs, .

+3

"" - , , Unicode .

Unicode UTF-8 - ( , "endiannes", UTF-16, UTF-16 , ), (, UTF-16 Windows, wchar_t - Visual ++).

Visual ++, ccs fopen() ( _wfopen()), , . "ccs=UTF-8" UTF-8.
MSDN fopen(), :

fopen Unicode. Unicode, ccs, fopen, .

fp = fopen("newfile.txt", "rt+, ccs= encoding ");

: UNICODE, UTF-8 UTF-16LE.

, UNICODE UTF-16BE (.. big-endian UTF-16); .


, Unicode UTF-8 ( Visual Studio 2013):

wchar_t name[] = L"‎中國哲學書電子化計劃";
FILE * file = fopen("C:\\TEMP\\ChineseLetters.txt", "wt, ccs=UTF-8");
...check for error...

fwrite(name, sizeof(wchar_t), _countof(name)-1, file);
fclose(file);

, Visual Studio , Unicode, , .
, Unicode, - " " ( Windows/++ ).

, _countof() sizeof() fwrite().
:

fwrite(name, sizeof(wchar_t), sizeof(name), file);

, wchar_t s, ( , MSVC, sizeof(wchar_t) == 2, .. a wchar_t - char s, .. ).

, -1 wchar_t s, NUL -terminating wchar_t Unicode .
( Unicode UTF-16 wchar_t wcslen(), wchar_t, NUL).

UTF-8 Word:

Chinese Text From UTF-8 File Showed in MS Word

+2

All Articles