win32

#include <Windows.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#pragma warning(disable:4996)

bool ConvertToWideFromUTF8orACP(char* strData, wchar_t* w_strData, int w_strDataLen)
{
    int nSize = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, strData, -1, w_strData, w_strDataLen);
    if (nSize == 0)
    {
        nSize = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, strData, -1, w_strData, w_strDataLen);
    }    
    return nSize - 1;
  
}

int main()
{
    char cs[] = "Hello大家好";
    printf("%s
", cs);
    wchar_t* lpWideCharStr = new wchar_t[sizeof(cs)];
    memset(lpWideCharStr, 0, sizeof(cs));
    int nSize = ConvertToWideFromUTF8orACP(cs, lpWideCharStr,sizeof(cs));
    _setmode(_fileno(stdout), _O_U16TEXT);
    if (nSize > 0)
    {
        wprintf(L"%s", lpWideCharStr);
    }   
    FILE* pf;
    pf = _wfopen(_FileName, L"a, ccs=UTF-8");
    fwprintf(pf, L"%ls", lpWideCharStr);
    delete[] lpWideCharStr;
    fflush(pf);
    fclose(pf);
}

 中文字符需要占到两个字节,所以一般以宽字节来处理。如果用多字节来存放宽字节的中文字符,那我们就需要使用MultiByteToWideChar来转换。

原文地址:https://www.cnblogs.com/strive-sun/p/14451111.html