如何在 Windows 中用 C++ 将 UTF-8 编码的字符串写入文件

NSA*_*NSA 7 c++ windows unicode file-io utf-8

我有一个字符串,其中可能包含或不包含 unicode 字符,我正在尝试将其写入 Windows 上的文件。下面我发布了一段示例代码,我的问题是,当我打开窗口并将值读回窗口时,它们都被解释为 UTF-16 字符。

char* x = "Fool";
FILE* outFile = fopen( "Serialize.pef", "w+,ccs=UTF-8");
fwrite(x,strlen(x),1,outFile);
fclose(outFile);

char buffer[12];
buffer[11]=NULL;
outFile = fopen( "Serialize.pef", "r,ccs=UTF-8");
fread(buffer,1,12,outFile);
fclose(outFile);
Run Code Online (Sandbox Code Playgroud)

如果我在写字板等中打开文件,这些字符也会被解释为 UTF-16。我做错了什么?

Han*_*ant 7

是的,当您指定文本文件应使用 UTF-8 编码时,CRT 隐式假定您将向文件写入 Unicode 文本。不这样做没有意义,你不需要 UTF-8。这将正常工作:

wchar_t* x = L"Fool";
FILE* outFile = fopen( "Serialize.txt", "w+,ccs=UTF-8");
fwrite(x, wcslen(x) * sizeof(wchar_t), 1, outFile);
fclose(outFile);
Run Code Online (Sandbox Code Playgroud)

或者:

char* x = "Fool";
FILE* outFile = fopen( "Serialize.txt", "w+,ccs=UTF-8");
fwprintf(outFile, L"%hs", x);
fclose(outFile);
Run Code Online (Sandbox Code Playgroud)