2

I writing a txt file using ofstream, from various reasons the file should have local encoding and not UTF8. The machine which process the file has different localizations then the target local.

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

regards,

Ilan

eLAN
  • 303
  • 5
  • 13

2 Answers2

2

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"); 
Mourad
  • 404
  • 4
  • 11
0

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

Community
  • 1
  • 1
MSalters
  • 173,980
  • 10
  • 155
  • 350