/*char* to wchar_t* */
wchar_t*strtowstr(char*str){
iconv_t cd=iconv_open("wchar_t","UTF-8");
if(cd==(iconv_t)-1){
return NULL;
}
size_t len1=strlen(str),len2=1024;
wchar_t*wstr=(wchar_t*)malloc((len1+1)*sizeof(wchar_t));
char*ptr1=str;
wchar_t*ptr2=wstr;
if((int)iconv(cd,&ptr1,&len1,(char**)&ptr2,&len2)<0){
free(wstr);
iconv_close(cd);
return NULL;
}
*ptr2=L'\0';
iconv_close(cd);
return wstr;
}
我使用strerror(errno)
来获取错误消息,它说“ Arg列表太长”。我该如何解决?多亏了这些注释,我更改了上面的代码。我只使用该功能读取文本文件。我认为它报告错误是因为文件太大。所以我想知道如何对长字符串使用iconv。
根据手册页,当E2BIG
的空间不足时,您会得到*outbuf
。
我认为第五个参数应为bytes的数量。
wchar_t *utf8_to_wstr(const char *src) {
iconv_t cd = iconv_open("wchar_t", "UTF-8");
if (cd == (iconv_t)-1)
goto Error1;
size_t src_len = strlen(src); // In bytes, excludes NUL
size_t dst_len = sizeof(wchar_t) * src_len; // In bytes, excludes NUL
size_t dst_size = dst_len + sizeof(wchar_t); // In bytes, including NUL
wchar_t *buf = malloc(dst_size);
if (!buf)
goto Error2;
wchar_t *dst = buf;
if (iconv(cd, &(char*)src, &src_len, &(char*)dst, &dst_len) == (size_t)-1)
goto Error3;
*dst = L'\0';
iconv_close(cd);
return buf;
Error3:
free(buf);
Error2:
iconv_close(cd);
Error1:
return NULL;
}