字符编码的转换iconv

来源:互联网 发布:网络信息系统 编辑:程序博客网 时间:2024/05/18 21:39

要点:1、应用程序的iconv:采用命令行界面,允许将某种特定编码的文件转换为另一种编码;

            2、编程接口的iconv:包括3个函数

(具体使用man iconv 和man 3 iconv可了解)

1)命令行使用举例:

iconv -f gb2312 -t utf8 gbk_file.txt > utf8_file.txt

     说明:将gb2312编码的gbk_file.txt转化为utf8编码的utf8_file.txt

2)编程接口函数举例:

   功能:将字符串由utf8编码格式转化为gbk编码格式,输出新的文件所在路径(ps:记得用完之后手动free)

s8* convert_utf8_to_gbk(s8* utf8){iconv_t ich = -1;s8 *res = NULL;s8 *utf8p = utf8, *gbkp = NULL;size_t in = 0, out = 0;if('\0' == utf8[0] || NULL == utf8){printf ("string is NULL!\n");return NULL;}ich = iconv_open("GBK", "UTF-8");/* 相关函数一 */if (-1 == ich){printf ("iconv_open() ERROR: %s\n", strerror(errno));return NULL;}in = strlen(utf8);out = in;res = (s8 *) malloc (out);if (NULL == res){printf ("malloc() ERROR!\n");return NULL}gbkp = res;memset (res, 0, out);if (-1 == iconv (ich, &utf8p, &in, &gbkp, &out))/* 相关函数二 */{printf ("iconv() ERROR: %s\n", strerror(errno));return NULL;}gbkp[0] = '\0';/* iconv()没有给字符串加上'\0' */iconv_close(ich);/* 相关函数三 */return res;}


0 0