Is there any built-in function that convert wstring or wchar_t* to UTF-8 in Linux?

Amir Saniyan picture Amir Saniyan · Sep 19, 2011 · Viewed 15k times · Source

I want to convert wstring to UTF-8 Encoding, but I want to use built-in functions of Linux.

Is there any built-in function that convert wstring or wchar_t* to UTF-8 in Linux with simple invokation?

Example:

wstring str = L"file_name.txt";
wstring mode = "a";
fopen([FUNCTION](str), [FUNCTION](mode)); // Simple invoke.
cout << [FUNCTION](str); // Simple invoke.

Answer

Cubbi picture Cubbi · Sep 27, 2011

If/when your compiler supports enough of C++11, you could use wstring_convert

#include <iostream>
#include <codecvt>
#include <locale>
int main()
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;
    std::wstring str = L"file_name.txt";
    std::cout << utf8_conv.to_bytes(str) << '\n';
}

tested with clang++ 2.9/libc++ on Linux and Visual Studio 2010 on Windows.