在C语言中使用libiconv进行编码转换的示例
2024-09-06 16:55:33
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)- == conversionDescriptor)
{
if (errno == EINVAL)
printf("Not supported from %s to %s.\n", fromCode, toCode);
else
printf("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 = (char *)malloc(sizeof(char) * BUFFER_SIZE);
const char *sourcePtr = sourceBuffer;
size_t destinationBufferSize = BUFFER_SIZE * , 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] = '\0';
printf(destinationBuffer);
fwrite(destinationBuffer, sizeof(char), characterCount, outputFile);
free(sourceBuffer);
free(destinationBuffer);
fclose(outputFile);
}
else
printf("Cannot open file: %s.\n", filename);
fclose(inputFile);
}
else
printf("Cannot open file: %s.\n", filename);
iconv_close(conversionDescriptor);
}
system("pause");
return ;
}
参考链接:unnonouno/iconvpp: wrapper library of iconv for c++
最新文章
- 国内maven镜像,快的飞起
- iNeedle产品介绍
- GUN485项目的总结
- 支持多人协作的在线免费作图工具:ProcessOn
- 用css3写出来的进度条
- Pick-up sticks - POJ 2653 (线段相交)
- 正则如何匹配div下的所有<;li>;标签?
- SharePoint 2016 每天预热脚本介绍
- Server.MapPath找不到命名空间,解决办法
- 一篇迟到的gulp文章
- Load data local infile 实验报告
- Core Expression
- webapi快速开发框架
- Python之禅的翻译和解释
- java解惑--摘要
- WebStrom2018注册码
- C++ new运算符
- LuoguP2680 运输计划
- [Unity优化]UI优化(一):RaycastTarget
- mysql \G
热门文章
- POJ——2251Dungeon Master(三维BFS)
- [POJ1143]Number Game
- BZOJ3261 最大异或和 【可持久化trie树】
- 刷题总结——书架(bzoj1861)
- 论文笔记:Ten years of pedestrian detection, what have we learned?
- P1651 塔 (动态规划)
- Java中NIO、BIO、AIO相关概念及应用场景
- bzoj2324 [ZJOI2011]营救皮卡丘 费用流
- 【bzoj4004】【JLOI2015】装备购买 (线性基+高斯消元)
- UVa1363 Joseph&#39;s Problem