wofstream not writing Japanese Characters in file

332 Views Asked by At

I'm trying to write Japanese to a file using wofstream and wstring. Unfortunately, wofstream doesn't write Japanese characters to the file when compiled with g++ or clang++ (in WSL and Windows 10) with no additional flags.

#include <fstream>

int main() {
    std::wofstream file("file.txt");
    std::wstring str = L"Onee-chan, Ohayou!";
    file << str;
}

file.txt

Onee-chan, Ohayou!

But,

#include <fstream>

int main() {
    std::wofstream file("file.txt");
    std::wstring str = L"お姉ちゃん、おはよう!";
    file << str;
}

file.txt has 0 bytes of size.

BUT when compiled with MSVC with the following code,

#include <fstream>

int main() {
    std::ofstream file("file.txt");
    std::string str = "お姉ちゃん、おはよう!";
    file << str;
}

file.txt has:
お姉ちゃん、おはよう!

Want my application to run on both linux and Windows. It works on windows with msvc (using string, char and fstreams [that's good]). I don't think MSVC is on linux, therefore I tried using wstring, wchat_t and wfstreams with g++ (in WSL and Windows cmd) but they don't write Japanese to the files.

Any suggestions on how to get through this.

(For Example: msvc like settings for g++(preferred) or any changes in the code(not preferred))

0

There are 0 best solutions below