在linux中,我创建了一个带有土耳其语字符的文件,并将文件字符集更改为"ISO-8859-9"。使用下面的 cpp,我正在尝试将其转换为 UTF-8。但是 iconv 返回空的输出缓冲区。但是"iconv"返回"inbytesleft",因为"0"表示在输入时完成转换。这里可能有什么错误?
我的 linux 文件格式: [root@osst212 cod]# 文件测试.txt 测试.txt:ISO-8859 文本
[root@osst212 cod]# 猫测试.txt --> 在这里,我的腻子字符集设置是 ISO-8859-9 fıstıkçı şahap
#include <string>
#include <iostream>
#include <locale>
#include <cstdlib>
#include <fstream>
#include <string>
#include <sstream>
#include <iconv.h>
#include <cstring>
#include <cerrno>
#include <csignal>
using namespace std;
int main()
{
const char* lna = getenv("LANG");
cout << "LANG is " << lna << endl;
setlocale(LC_ALL, "tr_TR.ISO8859-9");
ifstream fsl("test.txt",ios::in);
string myString;
if ( fsl.is_open() ) {
getline(fsl,myString); }
size_t ret;
size_t inby = sizeof(myString); /*inbytesleft for iconv */
size_t outby = 2 * inby; /*outbytesleft for iconv*/
char* input = new char [myString.length()+1]; /* input buffer to be translated to UTF-8 */
strcpy(input,myString.c_str());
char* output = (char*) calloc(outby,sizeof(char)); /* output buffer */
iconv_t iconvcr = iconv_open("UTF-8", "ISO−8859-9");
if ((ret = iconv(iconvcr,&input,&inby,&output,&outby)) == (size_t) -1) {
fprintf(stderr,"Could not convert to UTF-8 and error detail is n",strerror(errno)); }
cout << output << endl;
raise(SIGINT);
iconv_close(iconvcr);
}
调用 iconv 后的局部变量如下所示,当我在 gdb 下运行时。您可以看到输出为空。
(gdb) bt
#0 0x00007ffff7224387 in raise () from /lib64/libc.so.6
#1 0x0000000000401155 in main () at stack.cpp:41
(gdb) frame 1
#1 0x0000000000401155 in main () at stack.cpp:41
41 raise(SIGINT);
(gdb) info locals
lna = 0x7fffffffef72 "en_US.UTF-8"
fsl = <incomplete type>
ret = 0
inby = 0
outby = 4
myString = "f375st375k347375 376ahap"
input = 0x606268 " 376ahap"
output = 0x60628c ""
iconvcr = 0x606a00
man 3 iconv
iconv()
函数一次转换一个多字节字符,对于每个字符转换,它按转换后的输入字节数递增*inbuf
递减*inbytesleft
,按转换后的输出字节数递增*outbuf
递减*outbytesleft
递减。
output
将更新为指向最初分配的缓冲区中下一个未使用的字节。
正确的用法
char* nextouput = output:
if ((ret = iconv(iconvcr, &input, &inby, &nextoutput, &outby)) == (size_t) -1) {
fprintf(stderr, "Could not convert to UTF-8 and error detail is n", strerror(errno)); }