如何在Linux中使用POSIX方法从文件中读取Unicode-16字符串?

Har*_*vey 5 linux windows unicode posix wchar-t

我有一个包含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()
Run Code Online (Sandbox Code Playgroud)

小智 6

最简单的方法是将文件从utf16转换为utf8本机UNIX编码,然后读取它,

iconv -f utf16 -t utf8 file_in.txt -o file_out.txt
Run Code Online (Sandbox Code Playgroud)

您还可以使用iconv(3)(请参阅man 3 iconv)使用C转换字符串.大多数其他语言也绑定到iconv.

您可以使用任何UTF-8语言环境,如en_US.UTF-8,它们通常是大多数Linux发行版的默认语言环境.


bob*_*nce 4

\n

(Windows 总是使用 UTF-16 吗?例如日文版本)

\n
\n\n

是的,NT 的 WCHAR 始终是 UTF-16LE。

\n\n

(\xe2\x80\x98 系统代码页\xe2\x80\x99,对于日语安装来说确实是 cp932/Shift-JIS,为了许多非 Unicode 原生的应用程序的利益,仍然存在于 NT 中, FAT32 路径等。)

\n\n

但是,wchar_t 不保证为 16 位,在 Linux 上也不会,使用 UTF-32 (UCS-4)。所以 wcstombs_l 不太可能高兴。

\n\n

正确的做法是使用像 iconv 这样的库将其读入您内部使用的任何格式 - 大概是 wchar_t。您可以尝试通过插入字节来自己破解它,但您可能会得到像代理这样的错误。

\n\n
\n

在我最新的 Ubuntu 和 Mac OS X 机器上运行“locale -a”会产生名称中带有 utf-16 的零个语言环境。

\n
\n\n

事实上,由于所有 \\0,Linux 无法使用 UTF-16 作为语言环境默认编码。

\n