且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-15 16:39:22

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

Yes, when you specify that the text file should be encoded in UTF-8, the CRT implicitly assumes that you'll be writing Unicode text to the file. Not doing so doesn't make sense, you wouldn't need UTF-8. This will work proper:

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);

或:

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