void Encoding::Open() {
cd_ = iconv_open(to_charset_, from_charset_); //from_charset_="GBK" to_charset_="UTF-8"
if (cd_ == (iconv_t) (-1)) {
printf(
"The conversion from %s to %s is not supported by the implementation.",
from_charset_, to_charset_);
cd_ = NULL;
}
}
int Encoding::ConvertCharset(char* inBuf, int inBufLen, char* outBuf,
int outBufLen) {
if (cd_ == NULL) {
printf("Please init iconv first.\n");
return -1;
}
if(inBuf == NULL || inBufLen == 0)
return 0;
if(outBuf == NULL || outBufLen == 0)
return 0;
char* tmpbuff = outBuf;
int tmplen = outBufLen;
size_t size = iconv(cd_, &inBuf, (size_t *) &inBufLen, &tmpbuff,
(size_t *) &tmplen);
if (size == (size_t) (-1)) {
if (errno == EILSEQ) {
printf(
"An invalid multibyte sequence has been encountered in the input.");
} else if (errno == E2BIG) {
printf("There is not sufficient room at *outbuf.");
} else if (errno == EINVAL) {
printf(
"An incomplete multibyte sequence has been encountered in the input.");
}
return -1;
}
return outBufLen - tmplen - 1;
}