首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将std::wstring写入C++文件的多平台方法

将std::wstring写入C++文件的多平台方法
EN

Stack Overflow用户
提问于 2016-05-23 23:51:25
回答 2查看 1.1K关注 0票数 17

我一直在努力做一些看起来很简单的事情:将内容写到std::wstring到磁盘。假设我有以下字符串,我想将其写入纯文本文件:

std::wstring s = L"输入法."; // random characters pulled from baidu.cn

  1. Using std::codecvt_utf8 locale

或boost

下面是我使用的代码:

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中,对于发行版的存储库来说,这是一个太新的版本。如果不设置区域设置,则不会向文件中写入任何内容(在两个系统上)。

  1. With 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部件会导致无法识别的垃圾写入文件。

显然,我在这里遗漏了一些东西:将该字符串写入文件的正确方式是什么?

EN

回答 2

Stack Overflow用户

发布于 2016-06-09 21:11:30

您可以使用截取的下一个代码。与您的代码的不同之处在于,在这里我使用了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";
}
票数 1
EN

Stack Overflow用户

发布于 2016-06-10 17:10:18

即使输入数据是Unicode,流类型也始终生成ASCII输出。首先,您应该设置输出的语言环境。只有在以后,你才应该向文件中写入任何内容。我想,这个例子应该会对你有所帮助。我是在Ubuntu上运行的。

#include <cstdio>
#include <cwchar>
#include <string>
#include <locale>

void write_string(FILE *fd, std::wstring str)
{
    std::fputws(str.c_str(), fd);
}

int main()
{
    setlocale(0, "");
    FILE *fd = std::fopen("./test.txt", "w");

    write_string(fd, L"输入法.");

    std::fclose(fd);

    return 0;
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37395399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档