我有一个包含 UNICODE-16 字符串的文件,我想将其读入 Linux 程序。这些字符串是根据 Windows 内部 WCHAR 格式编写的。 (Windows 总是使用 UTF-16 吗?例如在日语版本中)
我相信我可以使用原始读取来读取它们并使用 wcstombs_l 进行转换。但是,我不知道要使用什么区域设置。在我最新的 Ubuntu 和 Mac OS X 机器上运行“locale -a”会产生名称中带有 utf-16 的零个语言环境。
有没有更好的办法?
更新:正确的答案和下面的其他答案帮助我指出使用 libiconv。这是我用来进行转换的函数。我目前将它放在一个类中,该类将转换为一行代码。
// Function for converting wchar_t* to char*. (Really: UTF-16LE --> UTF-8)
// It will allocate the space needed for dest. The caller is
// responsible for freeing the memory.
static int iwcstombs_alloc(char **dest, const wchar_t *src)
{
iconv_t cd;
const char from[] = "UTF-16LE";
const char to[] = "UTF-8";
cd = iconv_open(to, from);
if (cd == (iconv_t)-1)
{
printf("iconv_open(\"%s\", \"%s\") failed: %s\n",
to, from, strerror(errno));
return(-1);
}
// How much space do we need?
// Guess that we need the same amount of space as used by src.
// TODO: There should be a while loop around this whole process
// that detects insufficient memory space and reallocates
// more space.
int len = sizeof(wchar_t) * (wcslen(src) + 1);
//printf("len = %d\n", len);
// Allocate space
int destLen = len * sizeof(char);
*dest = (char *)malloc(destLen);
if (*dest == NULL)
{
iconv_close(cd);
return -1;
}
// Convert
size_t inBufBytesLeft = len;
char *inBuf = (char *)src;
size_t outBufBytesLeft = destLen;
char *outBuf = (char *)*dest;
int rc = iconv(cd,
&inBuf,
&inBufBytesLeft,
&outBuf,
&outBufBytesLeft);
if (rc == -1)
{
printf("iconv() failed: %s\n", strerror(errno));
iconv_close(cd);
free(*dest);
*dest = NULL;
return -1;
}
iconv_close(cd);
return 0;
} // iwcstombs_alloc()
最简单的方法是将文件从 utf16 转换为 utf8 本机 UNIX 编码,然后读取它,
iconv -f utf16 -t utf8 file_in.txt -o file_out.txt
您还可以使用 iconv(3)(请参阅 man 3 iconv)使用 C 转换字符串。大多数其他语言也与 iconv 绑定。
您可以使用任何 UTF-8 语言环境,例如 en_US.UTF-8,通常是默认语言环境
在大多数 Linux 发行版上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)