// Convert GBK encoded string to UTF-8 encoded string
int gbk2utf8(std::string &input) {
iconv_t cd = iconv_open(“UTF-8“, “GBK“); // Create an iconv handle for encoding conversion
if (cd == (iconv_t)(-1)) { // If iconv_open() call failed
// std::cerr (input.c_str()); // Define input buffer pointer
size_t inbytesleft = input.length(); // Define input buffer size
static threadlocal outbuf char[1024 * 32]; // Define output buffer
char* outptr = outbuf; // Define output buffer pointer
size_t outbytesleft = sizeof(outbuf); // Define output buffer size
while (inbytesleft > 0) {
// Convert data in the input buffer to data in the output buffer
size_t res = iconv(cd, &inbuf, &inbytesleft, &outptr, &outbytesleft);
if (res == (size_t)(-1)) { // If iconv() call failed
// std::cerr << “iconv() failed: “ << strerror(errno) << std::endl;
iconv_close(cd); // Close the iconv handle
return -1;
}
}
input = std::string(outbuf, sizeof(outbuf) - outbytesleft); // Save the data in the output buffer to the output parameter “output“
iconv_close(cd); // Close the iconv handle
return 0;
}