libiconv_sample.c
#include <stdio.h> #include <malloc.h> #include "libiconv/iconv.h" #ifdef _DEBUG #pragma comment(lib, "libiconv/libiconvd.lib") #else #pragma comment(lib, "libiconv/libiconv.lib") #endif #define BUFFER_SIZE 10 * 1024 * 1024 int main() { const char *toCode = "GBK", *fromCode = "UTF-8"; iconv_t conversionDescriptor = iconv_open(toCode, fromCode); if ((iconv_t)-1 == conversionDescriptor) { if (errno == EINVAL) printf("Not supported from %s to %s. ", fromCode, toCode); else printf("Unknown error. "); } 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 = (char *)malloc(sizeof(char) * BUFFER_SIZE); const char *sourcePtr = sourceBuffer; size_t destinationBufferSize = BUFFER_SIZE * 2, availableSpaceOfDestinationBuffer = destinationBufferSize; char *destinationBuffer = (char *)malloc(sizeof(char) * destinationBufferSize), *destinationPtr = destinationBuffer; size_t numberOfCharactersRead = fread(sourceBuffer, sizeof(char), BUFFER_SIZE, inputFile); iconv(conversionDescriptor, &sourcePtr, &numberOfCharactersRead, &destinationPtr, &availableSpaceOfDestinationBuffer); size_t characterCount = destinationBufferSize - availableSpaceOfDestinationBuffer; destinationBuffer[characterCount] = '