linux没有WideCharToMultiByte,MultiByteToWideChar,我们通常...

    技术2024-11-29  11

    Linux下面的没有命名为 WideCharToMultiByte() 和 MultiByteToWideChar() 函数,WideCharToMultiByte,MultiByteToWideChar是windows下的函数,在linux下也有类似的两个函数:mbstowcs() wcstombs() 值得注意的是:size_t mbstowcs(wchar_t *wcstr,const char *mbstr,size_t count);这个函数的第三个参数count,大小一定要是mbstr长度的2倍,否则出来的中文也会是乱码

     

    测试一下:

     

        setlocale(LC_ALL,"zh_CN.GB18030");    wchar_t wcstr[20] = L"字符测试123abc";    int len = wcslen(wcstr)+1;    printf("len = %d /n",len);    for(int i = 0; i < len; i++)        printf("0x%08x ",wcstr[i]);    printf("/n");    char str[55] = {0};        int n = wcstombs(str,wcstr,55);    if(-1 == n)    {    perror("wcstombs ");    exit(-1);    }        printf("n = %d/n",n);    for(int i = 0; i < n+1; i++)        printf("0x%08x ",str[i]);    printf("/n");        wchar_t wch[50]={0};    int m = mbstowcs(wch,str,n);        if(m == -1)    {    perror("Converting");    exit(-1);    }    printf("m = %d/n",m);    for(int i =0; i<m+1;i++)    printf("0x%08x ",wch[i]);    printf("/n");    return 0;}

     

    还有呢,转码还可以使iconv函数族,包含以下三个函数:iconv_t iconv_open(const char *tocode, const char *fromcode);

    size_t iconv(iconv_t cd,char **inbuf,size_t *inbytesleft,char **outbuf,size_t *outbytesleft);

    int iconv_close(iconv_t cd);

     

     

    测试一下:

    #include <stdio.h> #include <iconv.h> #include <string.h>

    #define BUFLEN 256

    char outbuf[BUFLEN]; char inbuf[BUFLEN] = "characters convertion";

    int main() {          char *pin = inbuf;      char *pout = outbuf;              int inlen = strlen(pin);      int outlen = BUFLEN;

         int retsize;

         iconv_t cd;

         cd = iconv_open("UTF-8", "GBK");

         if((iconv_t)-1 == cd) {              perror("iconv_open error");              return -1;      }

         retsize = iconv(cd, &pin, (size_t *)&inlen, &pout, (size_t *)&outlen);

         if((size_t)-1 == retsize) {              perror("iconv error");              return -2;         }

         if(outlen > 0) {              printf("%s/n", outbuf);      }

         iconv_close(cd);

         return 0; }

     

    另外

     

    关于Linux下转码的资料,这里比较全:

     

    http://www.360doc.com/content/11/0119/14/1317564_87612492.shtml

     

    仔细读,所有的问题基本都可以找到答案。

    最新回复(0)