linux如下有時候 字符需要進行編碼轉換(爬蟲將gbk轉爲utf-8編碼...)。通常可以選擇iconv函數。linux
終端如下 輸入 ios
man 3 iconv
我的看習慣了,msdn文檔以後感受linux如下的文檔的看的不是那麼爽了。函數
使用iconv函數進行轉碼,通常使用三個函數:iconv_open 、 iconv 、iconv_close三個函數。編碼
iconv_t iconv_open(const char* tocode,const char* fromcode)
終端如下輸入如下命令獲得系統支持的編碼:spa
iconv --list
size_t iconv(iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);
詳細函數內容可以查看這個網頁iconv_open iconv iconv_close函數文檔.net
使用完畢以後。需要關閉以前打開的句柄 :指針
int iconv_close(iconv_t cd);
樣例:
頭文件:CTranstlateString.h
#ifndef CTRANSTLATESTRING_H #define CTRANSTLATESTRING_H #include <string> #include <iostream> #include <iconv.h> class CTranstlateString { public: CTranstlateString(const char *to_encode , const char *from_encode); const char* Translate(const char* from, size_t flen); //字符串轉換 virtual ~CTranstlateString(); protected: private: char* fromstring; //字符串 char* tostring; // size_t fromleng;//帶轉換字符串預備長度 size_t toleng; // iconv_t handle; const char* InTranlsate(); //正真的字符串函數 }; #endif // CTRANSTLATESTRING_H
文件:CTranstlateString.cpp
#include <string.h> #include "CTranstlateString.h" using namespace std; CTranstlateString::CTranstlateString(const char *to_encode , const char *from_encode) { fromstring = new char[1]; fromleng = 1; tostring = new char[1]; toleng = 1; handle = iconv_open( to_encode , from_encode ); } CTranstlateString::~CTranstlateString() { delete[] fromstring; fromleng = 0; delete[] tostring; toleng = 0; iconv_close(handle); } const char* CTranstlateString::Translate(const char* from ,size_t flen) { if( fromleng < flen+1 ) //將待 編碼的字符串 存儲起來 { delete[] fromstring; fromstring = NULL; fromleng = 0; try { fromstring = new char[flen+1]; fromleng = flen + 1; } catch(...) { fromstring = NULL; fromleng = 0 ; return NULL; } } memset( fromstring , 0 , fromleng ); memcpy(fromstring, from, fromleng); size_t tlen = flen * 2; //分類 編碼後的字符串空間 if( toleng < tlen +1 ) { delete[] tostring; tostring = NULL; toleng = 0; try { tostring = new char[tlen + 1]; toleng = tlen + 1; } catch (...) { tostring = NULL; toleng = 0; return NULL; } } memset(tostring, 0, toleng); return InTranlsate(); //字符串轉碼 } const char* CTranstlateString::InTranlsate() { size_t outlen = toleng ; char *inbuf = fromstring; char *outbuf = tostring ; size_t inlen = fromleng; if ( -1 == iconv( handle ,&inbuf , &inlen , &outbuf , &outlen ) ) { return ""; } return tostring; //注意這裏的返回是重點 }