iconv_open、iconv和iconv_close函数使用示例

6180阅读 0评论2013-05-20 aquester
分类:C/C++


  1. bool isUtf8(const char* str)
  2. {
  3.     return ((0xEF == (unsigned char)(str[0]))
  4.          && (0xBB == (unsigned char)(str[1]))
  5.          && (0xBF == (unsigned char)(str[2])));
  6. }

  7. int code_convert(char *from_charset,char *to_charset, char *inbuf, size_t inlen, char *outbuf, size_t outlen)
  8. {
  9.     iconv_t cd;
  10.     char **pin = &inbuf;
  11.     char **pout = &outbuf;
  12.     
  13.     cd = iconv_open(to_charset, from_charset);
  14.     if (0 == cd) return -1;
  15.     if (-1 == iconv(cd, pin, &inlen, pout, &outlen))
  16.     {
  17.         int old_errno = errno;
  18.         iconv_close(cd);
  19.         errno = old_errno;
  20.         return -1;
  21.     }

  22.     iconv_close(cd);
  23.     return 0;
  24. }

  25. int toUtf8(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
  26. {
  27.     return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen);
  28. }

  29. int toGB2312(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
  30. {
  31.     return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen);
  32. }


上一篇:多写引发的思考
下一篇:libssh2编译错误(configure error: cannot find OpenSSL or Libgcrypt)解决方法