开发者

Force encoding when writing txt file with ofstream

I writing a txt file using ofstream, from various reasons the file should have local encoding and not UTF8. The machine whic开发者_如何学JAVAh process the file has different localizations then the target local.

is there a way to force the encoding when writing a file?

regards,

Ilan


You can call std::ios::imbue on your ofstream object to modify the locale. This won't affect the global locale.

std::ofstream os("output.txt");
std::locale mylocale(""); 
os.imbue(mylocale);
os << 1.5f << std::endl;
os.close();

Pay attention to the argument of std::locale constructor, it is implementation dependant. For example, the German locale could be :

std::locale mylocale("de_DE"); 

or

std::locale mylocale("German"); 


Well, given that it's Windows, you'd not have UTF8 anyway. But exactly what are you writing? Usually, you have a std::string in memory and write that to disk. The only difference is that \n in memory is translated to CR/LF (\r\n) on disk. That's the same translation everywhere.

You might encounter a situation where you're writing a std::wstring. In that case, it's determined by the locale. The default locale is the C locale, aka std::locale("C") orstd::locale::classic(). The local encoding (which you seem to want) isstd::locale("")`.

Other locales exist; see here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜