iconv 转码编程简介

来源:互联网 发布:淘宝是cs还是bs 编辑:程序博客网 时间:2024/05/30 05:18
glibc带了一套转码函数iconv,使用方便,可识别的码很多,如果程序需要涉及到编码之
间的转换,可考虑用它。

iconv命令的用法。

$ iconv --list # 显示可识别的编码名称
$ iconv -f GB2312 -t UTF-8 a.html > b.html # 转换GB2312编码的文件a.html为UTF-8
编码,存入b.html
$ iconv -f GB2312 -t BIG5 a.html > b.html # 转换GB2312编码的文件a.html为BIG5编
码,存入b.html
iconv编程涉及到以下glibc库的调用:

#include <iconv.h>

iconv_t iconv_open(const char *tocode, const char *fromcode);
int iconv_close(iconv_t cd);
size_t iconv(iconv_t cd,char **inbuf,
size_t *inbytesleft,char **outbuf,
size_t *outbytesleft);

在使用iconv转码的时候,首先用iconv_open获取转码句柄,然后调用iconv转码,转完了
后调用iconv_close关闭句柄。   
iconv函数中:
参数cd是用iconv_open调用返回的转码句柄;
参数inbuf指向需要转码的缓冲区;
参数inbytesleft是inbuf所保存的需要转码的字节数;
参数outbuf存放转码结果;
参数outbytesleft存放outbuf空间的大小。

如果调用成功,iconv返回转换的字节数(不可逆转调用的字节数,可逆转调用的字节数不
包括在内)。否则返回-1,并设置相应的errno。
iconv逐步扫描inbuf,每转换一个字符,就增加inbuf,减少inbytesleft,并将结果存入
outbuf,结果字节数存入outbytesleft。遇到下列情况将停止扫描并返回:

1. 多字节序列无效,这时候errno为EILSEQ,*inbuf指向第一个无效的字符;
2. 有字节留在inbuf尚未转换,errno为EINVAL;
3. outbuf空间不够,errno为E2BIG;
4. 正常转换完备。

对于iconv函数,还有两种调用情况:

1. inbuf或者*inbuf为NULL,outbuf和*outbuf不为NULL,iconv会设置转换状态为初始状
态,并保存转换序列到*outbuf。如果outbuf空间不足,errno会设置为E2BIG,返回(size
_t)(-1);
2. inbuf或者*inbuf为NULL,outbuf或者*outbuf也为NULL,iconv设置转换状态为初始状
态。

iconv命令的使用固然方便,可是如果转换过程中如果遇到问题则会停止转换,有时候我们
希望跳过不能转换的字节序列继续转换。以下的一段程序能实现这种功能。

/**
* siconv.cpp - A simple way to demostrate the usage of iconv calling
*
* Report bugs to marchday2004@yahoo.com.cn
* July 15th, 2006
*/
#include <iconv.h>
#include <stdio.h>
#include <string>
#include <stdarg.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/mman.h>

#ifdef DEBUG
#define TRACE(fmt, args...) fprintf(stderr, "%s:%s:%d:"fmt, /
__FILE__, __FUNCTION__, __LINE__, ##args)
#else
#define TRACE(fmt, args...)
#endif

#define CONVBUF_SIZE 32767

extern int errno;

void print_err(const char *fmt, ...)
{
va_list ap;

va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}

int print_out(const char* buf, size_t num)
{
if (num != fwrite(buf, 1, num, stdout)) {
  return -1;
}

return 0;
}

void print_usage() {

print_err("Usage: siconv -f encoding -t encoding [-c] "
  "input-file/n");
}

int iconv_string(const char *from, const char *to,
     const char *src, size_t len,
     ::std::string& result,
     int c = 0, size_t buf_size = 512)
{
iconv_t cd;

char *pinbuf = const_cast< char* >(src);
size_t inbytesleft = len;
char *poutbuf = NULL;
size_t outbytesleft = buf_size;

char *dst = NULL;
size_t retbytes = 0;
int done = 0;
int errno_save = 0;

if ((iconv_t)-1 == (cd = iconv_open(to, from))) {
  return -1;
}

dst = new char[buf_size];

while(inbytesleft > 0 && !done)  {
  poutbuf = dst;
  outbytesleft = buf_size;
 
  TRACE("TARGET - in:%p pin:%p left:%d/n", src, pinbuf, inbytesleft);
  retbytes = iconv(cd, &pinbuf, &inbytesleft, &poutbuf, &outbytesleft);
  errno_save = errno;
 
  if (dst != poutbuf)  {// we have something to write
   TRACE("OK - in:%p pin:%p left:%d done:%d buf:%d/n",
    src, pinbuf, inbytesleft, pinbuf-src, poutbuf-dst);
   result.append(dst, poutbuf-dst);
  }
 
  if (retbytes != (size_t)-1) {
   poutbuf = dst;
   outbytesleft = buf_size;
   (void)iconv(cd, NULL, NULL, &poutbuf, &outbytesleft);
  
   if (dst != poutbuf) {// we have something to write
     TRACE("OK - in:%p pin:%p left:%d done:%d buf:%d/n",
     src, pinbuf, inbytesleft, pinbuf-src, poutbuf-dst);
    result.append(dst, poutbuf-dst);
   }
  
   errno_save = 0;
   break;
  }
 
 
  TRACE("FAIL - in:%p pin:%p left:%d done:%d buf:%d/n",
   src, pinbuf, inbytesleft, pinbuf-src, poutbuf-dst);
 
  switch(errno_save)  {
  case E2BIG:
   TRACE("E E2BIG/n");
   break;
  case EILSEQ:
   TRACE("E EILSEQ/n");
   if (c) {
    errno_save = 0;
    inbytesleft = len-(pinbuf-src); // forward one illegal byte
    inbytesleft--;
    pinbuf++;
    break;
   }
  
   done = 1;
   break;
  case EINVAL:
   TRACE("E EINVAL/n");
   done = 1;
   break;
  default:
   TRACE("E Unknown:[%d]%s/n", errno, strerror(errno));
   done = 1;
   break;
  }
 
}

delete[] dst;
iconv_close(cd);

errno = errno_save;
return (errno_save) ? -1 : 0;
}

int conv_file_fd(const char* from, const char *to, int fd,
     ::std::string& result, int c)
{
struct stat st;
void *start;

if (0 != fstat(fd, &st)) {
  return -1;
}

start = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);

if (MAP_FAILED == start) {
  return -1;
}

if (iconv_string(from, to, (char*)start,
  st.st_size, result, c, CONVBUF_SIZE) < 0) {
  int errno_save = errno;
  munmap(start, st.st_size);
  TRACE("/n");
  errno = errno_save;
  return -1;
}

munmap(start, st.st_size);
return 0;
}

int conv_file(const char* from, const char* to,
     const char* filename, int c)
{
::std::string result;
FILE *fp;

if (NULL == (fp=fopen(filename, "rb"))) {
  print_err("open file %s:[%d]%s/n", filename,
   errno, strerror(errno));
  return -1;
}

if (conv_file_fd(from, to, fileno(fp), result, c) < 0)  {
  print_err("conv file fd:[%d]%s/n", errno, strerror(errno));
  fclose(fp);
  return -1;
}

print_out(result.data(), result.size());
fclose(fp);
return 0;
}

int main(int argc, char *argv[])
{
#ifdef TESTCASE
::std::string strA = "欢迎(welcome ^_^)来到(to)首都北京。";
::std::string strB = "大喊一声:We are chinese <=> 我们都是中国人。";

::std::string strC = strA.substr(0, 20) + strB.substr(0, 41);
::std::string result;
if (iconv_string("GBK", "UTF-8", strC.data(), strC.size(), result, 1) < 0)
{
  TRACE("ERROR [%d]%s/n", errno, strerror(errno));
}

TRACE("CONVERSION RESULT:");
result.append("/n");
print_out(result.data(), result.size());

return 0;
#else
::std::string from, to;
::std::string input_file;
int o;
int c = 0;

while (-1 != (c = getopt(argc, argv, "f:t:c")))
{
  switch(c) {
  case 'f':
   from = optarg;
   break;
  case 't':
   to = optarg;
   break;
  case 'c':
   c = 1;
   break;
  default:
   return -1;
  }
}

if (from.empty() || to.empty() || optind != (argc-1))
{
  print_usage();
  return -1;
}

input_file = argv[optind++];

return conv_file(from.c_str(), to.c_str(),
  input_file.c_str(), c);
#endif
}


可以用内存映像文件解决文件太大内存缓冲不够的情况。相对于iconv命令,加-c选项,以
忽略转换过程中可能引发的问题。

$ g++ -o siconv siconv.cpp
如果在命令行加了-DDEBUG选项,会编译进调试语句,如果加了-DTESTCASE选项,则仅会编
译对iconv_string函数测试的情况。