/****************************************************************************
@File Name: convert.h
@Author: wangzhicheng
@mail: 2363702560@qq.com
@Created Time: Fri 24 Feb 2017 04:44:36 PM CST
2017-02-26
@Brief convert a kind of character set to another kind
****************************************************************************/
#ifndef CONVERT_H
#define CONVERT_H
#include <iconv.h>
#include <string>
namespace charset_convert
{
using namespace std;
static const int MAXLEN = 1024;
class Convert
{
private:
iconv_t m_id;
public:
Convert();
~Convert();
/*
* @brief init iconv
* @return true if init ok
* */
bool Init(const string &from_set, const string &to_set);
/*
* @brief execute convertion
* @return true if convert ok
* */
bool convert(const string &src, string &dest);
};
}
#endif
/****************************************************************************
@File Name: convert.cpp
@Author: wangzhicheng
@mail: 2363702560@qq.com
@Created Time: Fri 24 Feb 2017 04:44:36 PM CST
2017-02-26
@Brief convert a kind of character set to another kind
****************************************************************************/
#include "convert.h"
namespace charset_convert
{
Convert::Convert()
{
m_id = 0;
}
/*
* @brief init iconv
* @return true if init ok
* */
bool Convert::Init(const string &from_set, const string &to_set)
{
m_id = iconv_open(to_set.c_str(), from_set.c_str());
return m_id;
}
/*
* @brief execute convertion
* @return true if convert ok
* */
bool Convert::convert(const string &src, string &dest)
{
size_t inlen = src.size();
if(inlen > MAXLEN) return false;
char *p_src = (char *)src.c_str();
dest.assign(MAXLEN << 1, 0);
size_t outlen = dest.size();
char *p_dest = (char *)dest.c_str();
if(iconv(m_id, &p_src, &inlen, &p_dest, &outlen) < 0) return false;
if(inlen) return false;
return true;
}
Convert::~Convert()
{
if(m_id)
{
iconv_close(m_id);
m_id = 0;
}
}
}
/****************************************************************************
@File Name: test.cpp
@Author: wangzhicheng
@mail: 2363702560@qq.com
@Created Time: Fri 24 Feb 2017 05:02:03 PM CST
2017-02-26
****************************************************************************/
#include "convert.h"
#include <iostream>
using namespace charset_convert;
int main()
{
Convert convert;
if(!convert.Init("utf-8", "gb2312"))
{
cerr << "convert init failed...!" << endl;
return -1;
}
string src = "I am linux...!";
string dest;
if(convert.convert(src, dest))
{
cout << dest << endl;
return 0;
}
return -1;
}
CC=g++
all:
$(CC) -std=c++11 -g -o convertTest test.cpp convert.h convert.cpp
charset convert
最新推荐文章于 2023-06-21 16:57:21 发布