C语言libiconv编程,在C语言中使用libiconv进行编码转换的示例

#include #include"libiconv/iconv.h"

#pragma comment(lib, "libiconv/libiconv.lib")

#define INPUT_BUFFER_SIZE 1024

intmain()

{const char *toCode = "GBK", *fromCode = "UTF-8";

iconv_t conversionDescriptor=iconv_open(toCode, fromCode);if (-1 ==conversionDescriptor)

{if (errno ==EINVAL)

printf("Not supported from %s to %s.\n", fromCode, toCode);elseprintf("Unknown error.\n");

}else{const char *filename = "text_utf-8.txt";

FILE*inputFile = fopen(filename, "r");if(inputFile)

{

filename= "text_gbk.txt";

FILE*outputFile = fopen(filename, "w");if(outputFile)

{char sourceBuffer[INPUT_BUFFER_SIZE], destinationBuffer[INPUT_BUFFER_SIZE * 2];char *sourcePtr = sourceBuffer, *destinationPtr =destinationBuffer;

size_t numberOfObjects;

size_t totalSpaceOfDestinationBuffer= INPUT_BUFFER_SIZE * 2, availableSpaceOfDestinationBuffer =totalSpaceOfDestinationBuffer;while (!feof(inputFile))

{

numberOfObjects= fread(sourceBuffer, sizeof(char), INPUT_BUFFER_SIZE, inputFile);while (numberOfObjects > 0)

{

size_t ret= iconv(conversionDescriptor, &sourcePtr, &numberOfObjects, &destinationPtr, &availableSpaceOfDestinationBuffer);if ((size_t)-1 ==ret)

{++sourcePtr;--numberOfObjects;

}

size_t elementCount= totalSpaceOfDestinationBuffer -availableSpaceOfDestinationBuffer;

destinationBuffer[elementCount]= ‘\0‘;

printf(destinationBuffer);

fwrite(destinationBuffer,sizeof(char), elementCount, outputFile);

}

}

fclose(outputFile);

}elseprintf("Cannot open file: %s.", filename);

fclose(inputFile);

}elseprintf("Cannot open file: %s.", filename);

iconv_close(conversionDescriptor);

}

system("pause");return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值