我一直在努力做一些看起来很简单的事情:将内容写入 std::wstring 到磁盘。假设我有以下要写入纯文本文件的字符串:
std::wstring s = L"输入法."; // random characters pulled from baidu.cn
- 使用
std::codecvt_utf8
或提升语言环境
这是我使用的代码:
std::wofstream out(destination.wstring(), std::ios_base::out | std::ios_base::app);
const std::locale utf8_locale = std::locale(std::locale(), new boost::locale::utf8_codecvt<wchar_t>());
out.imbue(utf8_locale);
// Verify that the file opened correctly
out << s << std::endl;
这在 Windows 上运行良好,但遗憾的是我在 Linux 上编译它:codecvt_utf8
在通常发行版提供的编译器上尚不可用,并且 Boost:Locale 仅包含在 Boost 1.60 中.0 对于发行版的存储库来说又是一个太新的版本。如果不设置语言环境,则不会将任何内容写入文件(在两个系统上)。
- 使用 fwrite
下一次尝试:
FILE* out = fopen("test.txt", "a+,ccs=UTF-8");
fwrite(s.c_str(), wcslen(s.c_str()) * sizeof(wchar_t), 1, out);
fclose(out);
这适用于 Windows,但不会向 Linux 上的文件写入任何内容。我也尝试以二进制模式打开文件,但这并没有改变任何东西。不设置 ccs
部分会导致无法识别的垃圾被写入文件。
我显然在这里遗漏了一些东西:将该字符串写入文件的正确方法是什么?
最佳答案
您可以使用下一个代码被剪断。与您的代码不同的是,这里我使用了 std::codecvt_utf8 而不是 boost::locale....
#include <locale>
#include <codecvt>
----
std::wstring s = L"输入法.";
const std::locale utf8_locale = std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
myfile.open("E:/testFile.txt");
if (myfile.is_open())
{
myfile.imbue(utf8_locale);
myfile << s << endl;
myfile.close();
}
else
{
std::cout << "Unable to open file";
}
关于c++ - 在 C++ 中将 std::wstring 写入文件的多平台方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37395399/