您的位置:首页 > 其它

ofstream 处理wchar写文件保留unicode格式

2014-06-17 11:58 337 查看
std::ofstream recordFile;
recordFile.open(Wstr(recordName).Buf(), std::ios::out| std::ios::binary);
if (recordFile.is_open())
{
recordFile.write("\xff\xfe",2);
recordFile.write((const char *)content.c_str(),content.size()*2);
recordFile.close();
}
else
{
LOG(LS_ERROR) << "chatrecord: save error on opening file";
return 1;
}


1 使用ofstream,也可以处理wchar_t 格式的文件经,

1.1 不可使用wofstream,虽然处理文件名没有问题,但文件内容需要额外处理,如设置locale("chs"),最后输出的文件中,都是按照gb2312存储汉字,不是unicode。使用wofstream存储汉字并保留unicode 编码需再查询

2 换行符需要使用 L"\r\n",文件中编码为0d 00 0a 00

3 open函数中要保留 binary ,否则 \n 字符在最后的文件中是 0D 0A 00, L"\r\n" 就变成 0D 00 0D 0A 00

4 写文件内容前,先写入BOM。

5 由于用ofstream 写文件,而存储文件内容的变量时wstring,需要强转类型,按字节写入。

6 open以后一定要判断一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: