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;
}