wofstream输入wstring总是坏流
std::wofstream stream;
stream.open("C:\\temp_info.txt");
stream.imbue(std::locale("chs"));
for(std::size_t index=0;index!=8000;++index)
{
stream<<string_data<<std::endl;//string_data是一个字符串,大约有30KB左右
if(!stream)
throw std::runtime_error("unknow_error");//index大于3000左右就坏流了
}
从不用wofstream,文件就是字节流,wofstream做了什么?
[code=c]
#include <boost/locale.hpp>//用boost的locale处理字符集转换
using boost::locale::conv;
ofstream file;
wstring string_data;//Unicode字符串
//...
//UTF-8编码:
file << utf_to_utf<char>( string_data );//使用boost::locale::conv::utf_to_utf
//或者:
file << from_utf( string_data, "utf-8" );//使用boost::locale::conv::from_utf
//GBK编码:
file<<from_utf( string_data, "gbk" );//使用boost::locale::conv::from_utf
#include <boost/locale.hpp>//用boost的locale处理字符集转换 using boost::locale::conv; ofstream file; wstring string_data;//Unicode字符串 //... //UTF-8编码: file << utf_to_utf<char>( string_data );//使用boost::locale::conv::utf_to_utf //或者: file << from_utf( string_data, "utf-8" );//使用boost::locale::conv::from_utf //GBK编码: file<<from_utf( string_data, "gbk" );//使用boost::locale::conv::from_utf //UTF-16 LE for( std::wstring::const_iterator it = string_data.begin(); it != string_data.end(); ++ it ) { file.put( static_cast<char>(*it) ).put( static_cast<char>((*it) >> 8) ); } //static_cast是为了去掉编译警告,也可以不加。 //或者用下面的代码,但不可靠: file.write( reinterpret_cast<char const *>(string_data.c_str()), string_data.size() * sizeof(wchar_t)); //UTF-16 BE: for( std::wstring::const_iterator it = string_data.begin(); it != string_data.end(); ++ it ) { file.put( static_cast<char>((*it) >> 8) ).put( static_cast<char>(*it) ); }