1. 程式人生 > >C語言編碼轉換gb2312 to utf8,utf8 to gb2312 代碼,GCC編譯,支持Windows、Linux

C語言編碼轉換gb2312 to utf8,utf8 to gb2312 代碼,GCC編譯,支持Windows、Linux

inb style fine mem amp blog linu print from

編譯:gcc -o f.exe f.c -liconv

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <iconv.h>
#define OUTLEN 255

main()
{
    char *in_utf8 = "姝e?ㄥ??瑁?";
    char *in_gb2312 = "你是誰";
    char out[OUTLEN];
    int
rc; //unicode碼轉為gb2312碼 rc = u2g(in_utf8,strlen(in_utf8),out,OUTLEN); //printf("unicode-->gb2312 out=%sn",out); //gb2312碼轉為unicode碼 rc = g2u(in_gb2312,strlen(in_gb2312),out,OUTLEN); printf("gb2312-->unicode out=%sn",out); } /*代碼轉換:從一種編碼轉為另一種編碼*/ int code_convert(char *from_charset,char
*to_charset,char *inbuf,int inlen,char *outbuf,int outlen) { iconv_t cd; int rc; char **pin = &inbuf; char **pout = &outbuf; cd = iconv_open(to_charset,from_charset); if (cd==0) return -1; memset(outbuf,0,outlen); if (iconv(cd,pin,&inlen,pout,&outlen)==-1
) return -1; iconv_close(cd); return 0; } /*UNICODE碼轉為GB2312碼*/ int u2g(char *inbuf,int inlen,char *outbuf,int outlen) { return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen); } /*GB2312碼轉為UNICODE碼*/ int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen) { return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen); }

C語言編碼轉換gb2312 to utf8,utf8 to gb2312 代碼,GCC編譯,支持Windows、Linux