我有一个包含 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()