如何在C ++中使用UTF-8编码的string写入Windows中的文件

我有一个string,可能或不可能有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); 

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

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

要么:

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

如果你使用C++11标准,很容易(因为有很多附加的东西像"utf8" ,它永远解决了这个问题)。

但是,如果您想要使用较老的标准使用多平台代码,则可以使用此方法来写入流:

  1. 阅读有关UTF转换器的文章
  2. 从上面的源代码添加stxutif.h到你的项目
  3. 以ANSI模式打开文件,并将BOM添加到文件的开头,如下所示:

     std::ofstream fs; fs.open(filepath, std::ios::out|std::ios::binary); unsigned char smarker[3]; smarker[0] = 0xEF; smarker[1] = 0xBB; smarker[2] = 0xBF; fs << smarker; fs.close(); 
  4. 然后以UTF文件格式打开文件并在其中写下你的内容:

     std::wofstream fs; fs.open(filepath, std::ios::out|std::ios::app); std::locale utf8_locale(std::locale(), new utf8cvt<false>); fs.imbue(utf8_locale); fs << .. // Write anything you want...