Ubuntu上的库ICU不想从Unicode转换为Windows-1251

Library ICU on Ubuntu doesn't want to convert from Unicode to windows-1251

本文关键字:Unicode 转换 Windows-1251 不想 ICU Ubuntu      更新时间:2023-10-16

我正在使用ICU库,我需要从Unicode转换为Windows-1251,我写了此简单代码:

#include <unicode/unistr.h>
#include <unicode/ucnv.h>
int main(int argc, char** argv)
{
    UErrorCode status = U_ZERO_ERROR;
    UConverter *pConvert = ucnv_open("windows-1251", &status);
    if (status)
    {
        printf("Failed to obtain char set converter: %drn", status);
        return false;
    }
}

我总是会遇到此错误:"在创建UConverter对象期间,无法获得Char Set ....."。

如何解决此错误?我在Google中搜索,但什么也没找到。

我使用此代码获取了别名文件中所遏制的所有可用转换器的列表:

for(int i = 0; i < ucnv_countAvailable(); ++i)
    {
        printf("   %s  n", ucnv_getAvailableName(i));
    }

我在此列表中没有找到" Windows-1251"。如何添加此编码?

您需要使用宏U_SUCCESS,而不仅仅是测试status。负错误代码是ICU中的警告:

typedef enum UErrorCode {
  // ...
  U_AMBIGUOUS_ALIAS_WARNING = -122

这很好:

auto converter = ucnv_open("windows-1251", &error);
if (U_SUCCESS(error))
{
  printf("Success! %sn", ucnv_getName(converter, &error));
} 

并打印出来:

Success! ibm-5347_P100-1998

您获得"模棱两可"警告的原因是因为" Windows-1251"是一个以上的规范名称(ibm-5347_P100-1998ibm-1251_P100-1995(的别名。您可以通过使用"别名"功能更新样本来看到此内容:

int main()
{
  UErrorCode error{ U_ZERO_ERROR };
  const auto n = ucnv_countAvailable();
  for (int i = 0; i < n; ++i)
  {
    auto s = ucnv_getAvailableName(i);
    const auto m = ucnv_countAliases(s, &error);
    if (U_SUCCESS(error))
    {
      for (int j = 0; j < m; ++j)
      {
        auto a = ucnv_getAlias(s, j, &error);
        if (U_SUCCESS(error) && strstr(a, "windows-1251"))
          printf("%s --> %sn", s, a);
      }
    }
  }
}

(删除 strstr调用以查看所有名称/别名的很长列表(。