CentOS下UTF8和GBK的互转

来源:互联网 发布:温度监控软件 编辑:程序博客网 时间:2024/06/05 17:32

忘记转自哪里了,自己做了下测试感觉好用,记一下。

我在windows下新建Source.cpp

#include <iconv.h>  #include <stdlib.h>  #include <stdio.h>  #include <unistd.h>  #include <fcntl.h>  #include <string.h>  #include <sys/stat.h>  /*Title: Convert code between utf-8 and gbkDate:2016-02-01Test Environment:[1]CentOS 6.5 64bits[2]libiconv 1.14Prerequisite:[1]使用下面的命令locale -a|grep zh_CN查看下面的信息是否存在zh_CNzh_CN.gb18030zh_CN.gb2312zh_CN.gbkzh_CN.utf8*/int code_convert(char *from_charset, char *to_charset, char *inbuf, size_t inlen,char *outbuf, size_t outlen) {iconv_t cd;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);*pout = '\0';return 0;}int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen);}int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen);}int main(void) {char *s = "中国";int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);char buf[10];g2u(s, strlen(s), buf, sizeof(buf));write(fd, buf, strlen(buf));close(fd);fd = open("test.txt2", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);char buf2[10];u2g(buf, strlen(buf), buf2, sizeof(buf2));write(fd, buf2, strlen(buf2));close(fd);return 1;}


然后,通过CMake移到CentOS上测试通过

project(GBK2UTF8)  cmake_minimum_required(VERSION 2.8)  SET( CMAKE_VERBOSE_MAKEFILE ON )  #For search iconvINCLUDE_DIRECTORIES(/usr/local/include)LINK_DIRECTORIES(/usr/local/lib)#  aux_source_directory(. DIR_SRCS)  add_executable(GBK2UTF8 ${DIR_SRCS})      TARGET_LINK_LIBRARIES(GBK2UTF8 iconv)


0 0
原创粉丝点击