You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

41 lines
983 B

#include <iconv.h>
#include "ziconv.hpp"
using namespace iflytop;
string ZIconv::utf8_to_gb2312(const std::string& utf8_str) {
// 打开转换描述符
iconv_t cd = iconv_open("GB2312", "UTF-8");
if (cd == (iconv_t)-1) {
perror("iconv_open failed");
exit(EXIT_FAILURE);
}
// 输入字符串
const char* in_str = utf8_str.c_str();
size_t in_size = utf8_str.size();
// 输出缓冲区
size_t out_size = in_size * 2; // 假设输出的字节数不会超过输入的两倍
char* out_buf = new char[out_size];
char* out_str = out_buf;
// 进行转换
if (iconv(cd, const_cast<char**>(&in_str), &in_size, &out_str, &out_size) == (size_t)-1) {
perror("iconv failed");
iconv_close(cd);
delete[] out_buf;
exit(EXIT_FAILURE);
}
// 关闭转换描述符
iconv_close(cd);
// 获取转换后的字符串
std::string gb2312_str(out_buf, out_str - out_buf);
// 释放内存
delete[] out_buf;
return gb2312_str;
}