#include #include #include #include #include #include #include using namespace std; string toUTF8(const wstring& wstr) { int size_needed = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL); string str; str.resize(size_needed); WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), &str[0], str.size(), NULL, NULL); return str; } wstring toUTF16(const string& str) { int size_needed = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.c_str(), str.size(), NULL, 0); wstring wstr; wstr.resize(size_needed); MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.c_str(), str.size(), &wstr[0], wstr.size()); return wstr; } class WFile { public: FILE* ptr; WFile(const wstring& filename, const wstring& mode) { ptr = _wfopen(filename.c_str(), mode.c_str()); } ~WFile() { if (ptr) { fclose(ptr); } } }; int main() { setlocale(LC_CTYPE, ".OCP"); wstring wstr(L"\u221A"); wcout << wstr << endl; cout << toUTF8(wstr) << endl; WFile wtest(L"utf-16.txt", L"wb, ccs=UTF-16LE"); if (!wtest.ptr) { return EXIT_FAILURE; } fwprintf(wtest.ptr, L"\uFEFF"); fwprintf(wtest.ptr, L"%s", toUTF16(toUTF8(wstr)).c_str()); WFile test(L"utf-8.txt", L"wb, ccs=UTF-8"); if (!test.ptr) { return EXIT_FAILURE; } fprintf(test.ptr, "%s", toUTF8(wstr).c_str()); }