如何在Windows中使用C ++将UTF-8编码的字符串写入文件 [英] How do I write a UTF-8 encoded string to a file in windows, in C++

查看:524
本文介绍了如何在Windows中使用C ++将UTF-8编码的字符串写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,可能有或可能没有unicode字符,我试图将其写入Windows上的文件。下面我已经张贴了一个样本位的代码,我的问题是,当我打开并读取值回退窗口,他们都被解释为UTF-16字符。

I have a string that may or may not have unicode characters in it, I am trying to write that to a file on windows. Below I have posted a sample bit of code, my problem is that when I fopen and read the values back out windows, they are all being interpreted as UTF-16 characters.

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

如果我在wordpad等中打开文件,字符也被解释为UTF-16。做错了?

The characters are also interpreted as UTF-16 if I open the file in wordpad etc. What am I doing wrong?

推荐答案

是的,当您指定文本文件应以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);

这篇关于如何在Windows中使用C ++将UTF-8编码的字符串写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆