CentOS下UTF8和GBK的互转

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

我在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 gbk
Date:2016-02-01
Test Environment:
[1]CentOS 6.5 64bits
[2]libiconv 1.14
Prerequisite:
[1]使用下面的命令
locale -a|grep zh_CN
查看下面的信息是否存在
zh_CN
zh_CN.gb18030
zh_CN.gb2312
zh_CN.gbk
zh_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 iconv
INCLUDE_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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值