wchar_t与char相互转换(跨平台)

时间:2021-07-01 20:14:02
#if (defined WIN32) ||  (defined _WIN32)
#include<Windows.h>
#else
#include<unistd.h> 
#include<sys/types.h>
#include<strings.h>
#endif

#include <limits.h>
#include <locale.h>

int Logger::wc2mbs(wchar_t *wc,unsigned int wc_size,char *mbs)
{
    int mbs_size;
#if (defined WIN32) ||  (defined _WIN32)
    setlocale(LC_ALL,"chs");
#else
    setlocale(LC_ALL,"zh_CN.gbk");
#endif

    if(wc_size==0)
        wc_size=UINT_MAX;

    mbs_size=wcstombs(0,wc,wc_size);

    if(mbs!=0)
        mbs_size=wcstombs(mbs,wc,wc_size);

    return mbs_size;
}

int Logger::mbs2wc(char *mbs,unsigned int mbs_size,wchar_t *wc)
{
    int wc_size;
#if (defined WIN32) ||  (defined _WIN32)
    setlocale(LC_ALL,"chs");
#else
    setlocale(LC_ALL,"zh_CN.gbk");
#endif

    if(mbs_size==0)
        mbs_size=UINT_MAX;

    wc_size=mbstowcs(0,mbs,mbs_size);

    if(wc!=0)
        wc_size=mbstowcs(wc,mbs,mbs_size);

    return wc_size;
}