在C/C++裡面使用iconv function包含下列三步驟:
1. 用iconv_open建立一個iconv_t的變數
2. 呼叫iconv執行轉換
3. 用iconv_close來結束iconv_t的變數
下面這一段code是把iconv包成一個function方便使用:
string pwtIconv(string buf, string fromCode, string toCode)
{
iconv_t cd;
char tmp[1000];
string outBuf;
size_t inBytesLeft, outBytesLeft;
const char *inTmp;
char *outTmp;
cd = iconv_open(toCode.c_str(), fromCode.c_str());
if(cd == ((iconv_t) - 1))
{
if(errno == EINVAL)
cout << "no conversion from " << toCode << " to " << fromCode << endl;
else
cout << "conversion setup error" << endl;
fflush(stdout);
return "";
}
//type conversion
inTmp = buf.c_str();
outTmp = tmp;
//set initial length of in and out string
inBytesLeft = buf.length() + 1;
outBytesLeft = 1000;
while(inBytesLeft > 0)
{
size_t iconv_value;
iconv_value = iconv(cd, &inTmp, &inBytesLeft, &outTmp, &outBytesLeft);
if(iconv_value == (size_t) - 1)
{
cout << "some error" << endl;
fflush(stdout);
break;
}
}
outBuf = tmp;
iconv_close(cd);
return outBuf;
}
有些錯誤檢查沒有很嚴謹,但是資料正常應該是能運作。
參考資料 :
http://www.gnu.org/software/libtool/manual/libc/iconv-Examples.html#iconv-Examples
沒有留言:
張貼留言