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