/********************************************************
** 功能说明 : 字符串编码之间的互相转换
** 输入参数 : fcharset -- 输入格式 tcharset -- 输出格式
** 输入参数 : inbuf -- 输入串 inlen -- 输入长度
** 输入参数 : outlen -- 输出长度
** 输出参数 : outbuf -- 输出串
** 返回参数 : 0 -- 成功 非零 -- 失败
********************************************************/
int
CodeConvert (
char* fcharset, char* tcharset,
char* inbuf, int inlen,
char* outbuf, int outlen
) {
iconv_t vIconv;
char** vPin = &inbuf;
char** vPout = &outbuf;
/* 判断参数 */
if (
fcharset == NULL || tcharset == NULL
|| inbuf == NULL || outbuf == NULL
|| strlen(inbuf) == 0 || inlen == 0
|| outlen == 0
) {
printf("parameter is error!pleaase check your parameter is right?\n");
return -1;
}
/* 以特定编码格式打开 */
vIconv = iconv_open(tcharset, fcharset);
if (vIconv == (iconv_t)(-1))
{
printf("iconv_open error!\n");
return -2;
}
if (iconv(vIconv, vPin, (unsigned int *)&inlen, vPout, (unsigned int *)&outlen) == -1)
{
printf("iconv error!\n");
return -3;
}
iconv_close(vIconv);
return 0;
}
/********************************************************
** 功能说明 : 文件编码之间的互相转换
** 输入参数 : fcharset -- 输入格式 tcharset -- 输出格式
** 输入参数 : infile -- 输入文件名outfile -- 输出文件名
** 返回参数 : 0 -- 成功 -1 -- 失败
********************************************************/
int
CodeFileConvert (
char* fcharset, char* tcharset,
char* infile, char* outfile
) {
FILE* vInFile = NULL;
FILE* vOutFile = NULL;
char vBuffer[SIZE_BUFFER + 1];
char vInBuffer[SIZE_BUFFER + 1];
char vOutBuffer[SIZE_BUFFER + 1];
int inbuflen = 0;
int i = 0;
int infilelen = strlen(infile);
int outfilelen = strlen(outfile);
memset(vBuffer, 0x00, sizeof(vBuffer));
memset(vInBuffer, 0x00, sizeof(vInBuffer));
memset(vOutBuffer, 0x00, sizeof(vOutBuffer));
/* 判断参数 */
if (
fcharset == NULL || tcharset == NULL
|| infile == NULL || outfile == NULL
|| infilelen == 0 || infilelen > 255
|| outfilelen == 0 || outfilelen > 255
) {
printf("parameter is error!\n");
return -1;
}
if ((vInFile=fopen(infile, "rb")) == NULL)
{ /* 打开输入文件 */
printf("open infile error!\n");
return -1;
}
if ((vOutFile=fopen(outfile, "wb+")) == NULL)
{ /* 创建并打开输出文件 */
printf("open outfile error!\n");
fclose(vInFile);
return -1;
}
/* 取文件长度 */
fseek(vInFile, 0, SEEK_END);
infilelen = ftell(vInFile);
fseek(vInFile, 0, SEEK_SET);
/* 读取文件内容(256Bytes) */
while ((inbuflen=fread(vInBuffer, 1, SIZE_BUFFER_256, vInFile)) != 0)
{
i = inbuflen;
while (1)
{
if (i <= 0) break;
strncpy(vBuffer, vInBuffer, i);
if (CodeConvert(fcharset, tcharset, vBuffer, i, vOutBuffer, SIZE_BUFFER) == 0)
{
fseek(vInFile, -(inbuflen-i), SEEK_CUR);
break;
}
i--;
}
if (i <= 0)
{
/* 这里可以增加对外字之类的处理 */
printf("convert codeing failed!\n");
fclose(vInFile);
fclose(vOutFile);
return -1;
}
fwrite(vOutBuffer, 1, strlen(vOutBuffer), vOutFile);
memset(vInBuffer, 0x00, sizeof(vInBuffer));
memset(vOutBuffer, 0x00, sizeof(vOutBuffer));
}
fclose(vInFile);
fclose(vOutFile);
return 0;
}
|