Linux下字符集转换方法

本文介绍了一种使用C语言实现的GBK编码到UTF-8编码的转换方法,并提供了一个具体的示例程序。该程序利用iconv库进行编码转换,适用于Linux环境下文本文件的编码转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux是支持UTF-8的编码格式,别的编码格式需要转换一下,否则会出现乱码,Linux基本上支持所有的字符集类型,转化之前先用iconv --list看看Linux是否支持需要转化的格式

/*
 ============================================================================
 Name        : iconv.c
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <iconv.h>

int gbk2utf8(char *src, size_t *srclen, char *dest, size_t *destlen)
{
	// 每打开一次只能够用一次
	iconv_t cd = iconv_open("UTF8", "GBK");
	if (cd == (iconv_t) - 1)
	{
		printf("open iconv error %s\n", strerror(errno));
		return -1;
	}

	size_t rc = iconv(cd, &src, srclen, &dest, destlen);
	if (rc == (size_t) - 1)
	{
		printf("iconv error %s\n", strerror(errno));
		return -1;
	}
	iconv_close(cd);
	return 0;
}

int main(int arg, char *args[])
{
	if (arg < 2)
		return -1;
	FILE *p = fopen(args[1], "r");
	if (p == NULL)
	{
		printf("open %s error, %s\n", args[1], strerror(errno));
		return -1;
	}

	char buf[1024];// 定义一个buffer,存放读取到文件的内容
	char destbuf[1024];// 定义一个buffer,存放转化完字符串后的内容

	while (1) // 读取文件内容
	{
		memset(buf, 0, sizeof(buf));
		memset(destbuf, 0, sizeof(destbuf));
		if (fgets(buf, sizeof(buf), p) == NULL)
			break;
		size_t srclen = strlen(buf);
		size_t destlen = sizeof(destbuf);
		gbk2utf8(buf, &srclen, destbuf, &destlen);
		printf("%s", buf);
	}
	fclose(p);
	return EXIT_SUCCESS;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值