Linux下面的没有命名为 WideCharToMultiByte() 和 MultiByteToWideChar() 函数,WideCharToMultiByte,MultiByteToWideChar是windows下的函数,在linux下也有类似的两个函数:
mbstowcs()
wcstombs()
值得注意的是:
1 |
size_t mbstowcs(wchar_t *wcstr,const char *mbstr,size_t count); |
这个函数的第三个参数count,大小一定要是mbstr长度的2倍,否则出来的中文也会是乱码。
测试一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <wchar.h> int main(){ 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函数族,包含以下三个函数:
1 2 3 |
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); |
测试一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#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; size_t 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; } |
发表评论
要发表评论,您必须先登录。