一,命令行
在LINUX上进行编码转换时,可以利用iconv命令实现,这是针对文件的,即将指定文件从一种编码转换为另一种编码。
iconv命令用法如下:
iconv [选项...] [文件...]
1.输入/输出格式规范:
-f, --from-code=名称 原始文本编码
-t, --to-code=名称 输出编码
2.列举所有已知的字符集 -l, --list
3.输出控制:
-c 从输出中忽略无效的字符
-o, --output=FILE 输出文件
-s, --silent 关闭警告
--verbose 打印进度信息
例子:
iconv -f utf-8 -t gb2312 /server_test/reports/software_.txt > /server_test/reports/software_asserts.txt
二,函数运用
1.头文件
#include <iconv.h>
2.函数
(1) iconv_t iconv_open(const char *tocode, const char *fromcode);
此函数说明将要进行哪两种编码的转换,tocode是目标编码,fromcode是原编码,该函数返回一个转换句柄,供以下两个函数使用。
(2) size_t iconv(iconv_t cd,char **inbuf,size_t *inbytesleft,char **outbuf,size_t *outbytesleft);
此函数从inbuf中读取字符,转换后输出到outbuf中,inbytesleft用以记录还未转换的字符数,outbytesleft用以记录输出缓冲的剩余空间。
(3) int iconv_close(iconv_t cd);
此函数用于关闭转换句柄,释放资源。
3.例子: 用C语言实现的转换示例程序
#include "stdio.h" #include "string.h" #include "iconv.h" #include "stdlib.h" static int charset_convert(const char *from_charset, const char *to_charset, char *in_buf, size_t in_left, char *out_buf, size_t out_left) { iconv_t icd = (iconv_t)-1; size_t sRet = -1; char *pIn = in_buf; char *pOut = out_buf; size_t outLen = out_left; if (NULL == from_charset || NULL == to_charset || NULL == in_buf || 0 >= in_left || NULL == out_buf || 0 >= out_left) { return -1; } icd = iconv_open(to_charset, from_charset); if ((iconv_t)-1 == icd) { return -1; } sRet = iconv(icd, &pIn, &in_left, &pOut, &out_left); if ((size_t)-1 == sRet) { iconv_close(icd); return -1; } out_buf[outLen - out_left] = 0; iconv_close(icd); return (int)(outLen - out_left); } static int charset_convert_UTF8_TO_GB2312(char *in_buf, size_t in_left, char *out_buf, size_t out_left) { return charset_convert("UTF-8", "GB2312", in_buf, in_left, out_buf, out_left); } static int charset_convert_GB2312_TO_UTF8(char *in_buf, size_t in_left, char *out_buf, size_t out_left) { return charset_convert("GB2312-8", "UTF-8", in_buf, in_left, out_buf, out_left); } int main() { char *pIn = "hello 中国人"; char *pOut = NULL; size_t outLen = 0; size_t inLen = 0; int iRet = -1; inLen = strlen(pIn); outLen = inLen * 3; pOut = (char *)malloc(sizeof(char) * outLen); if (NULL == pOut) { return -1; } memset(pOut, 0, sizeof(char) * outLen); iRet = charset_convert_UTF8_TO_GB2312(pIn, (size_t)inLen, pOut, (size_t)inLen); if (-1 == iRet) { return -1; } printf("out = %s; ouLen = %d ", pOut, iRet); free(pOut); pOut = NULL; return 0; }
参考:http://blog.csdn.net/jnbbwyth/article/details/6991371