Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You shouldn't need to set your locale or set any special modes on the file if you just want to use fprintf. You simply have to use UTF-8 encoded strings.</p> <pre><code>#include &lt;cstdio&gt; #include &lt;codecvt&gt; int main() { std::wstring_convert&lt;std::codecvt_utf8_utf16&lt;wchar_t&gt;,wchar_t&gt; convert; std::string utf8_string = convert.to_bytes(L"кошка 日本国"); if(FILE *f = fopen("tmp","w")) fprintf(f,"%s\n",utf8_string.c_str()); } </code></pre> <p>Save the program as UTF-8 with signature or UTF-16 (i.e. don't use UTF-8 without signature, otherwise VS won't produce the right string literal). The file written by the program will contain the UTF-8 version of that string. Or you can do:</p> <pre><code>int main() { if(FILE *f = fopen("tmp","w")) fprintf(f,"%s\n","кошка 日本国"); } </code></pre> <p>In this case you must save the file as UTF-8 <em>without</em> signature, because you want the compiler to think the source encoding is the same as the execution encoding... This is a bit of a hack that relies on the compiler's, IMO, broken behavior.</p> <p>You can do basically the same thing with any of the other APIs for writing narrow characters to a file, but note that none of these methods work for writing UTF-8 to the Windows console. Because the C runtime and/or the console is a bit broken you can only write UTF-8 directly to the console by doing SetConsoleOutputCP(65001) and then using one of the <code>puts</code> variety of function.</p> <p>If you want to use wide characters instead of narrow characters then locale based methods and setting modes on file descriptors could come into play.</p> <pre><code>#include &lt;cstdio&gt; #include &lt;fcntl.h&gt; #include &lt;io.h&gt; int main() { if(FILE *f = fopen("tmp","w")) { _setmode(_fileno(f), _O_U8TEXT); fwprintf(f,L"%s\n",L"кошка 日本国"); } } </code></pre> <hr> <pre><code>#include &lt;fstream&gt; #include &lt;codecvt&gt; int main() { if(auto f = std::wofstream("tmp")) { f.imbue(std::locale(std::locale(), new std::codecvt_utf8_utf16&lt;wchar_t&gt;)); // assumes wchar_t is UTF-16 f &lt;&lt; L"кошка 日本国\n"; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload