为什么在转换UTF16后文件名有不同的字节 - > UTF8 - >在winapi的UTF16?

时间:2016-01-12 12:31:45

标签: c++ c winapi encoding utf-8

我有下一个档案: enter image description here

我使用ReadDirectoryChangesW来读取当前文件夹中的更改。 我得到了这个文件的路径:L“TESTӠ⬨☐.ipt”:

enter image description here

接下来,我想将其转换为utf8并返回:

std::string wstringToUtf8(const std::wstring& source) {
  const int size = WideCharToMultiByte(CP_UTF8, 0, source.data(), static_cast<int>(source.size()), NULL, 0, NULL, NULL);
  std::vector<char> buffer8(size);
  WideCharToMultiByte(CP_UTF8, 0, source.data(), static_cast<int>(source.size()), buffer8.data(), size, NULL, NULL);
}

std::wstring utf8ToWstring(const std::string& source) {
  const int size = MultiByteToWideChar(CP_UTF8, 0, source.data(), static_cast<int>(source.size()), NULL, 0);
  std::vector<wchar_t> buffer16(size);
  MultiByteToWideChar(CP_UTF8, 0, source.data(), static_cast<int>(source.size()), buffer16.data(), size);
}

int main() {
    // Some code with ReadDirectoryChangesW and 
    // ...
    // std::wstring fileName = "L"TEST Ӡ⬨☐.ipt""
    // ...

    std::string filenameUTF8 = wstringToUtf8(fileName);
    std::wstring filename2 = utf8ToWstring(filenameUTF8);
    assert(filenameUTF8 == filename2); // FAIL!
    return 0;
}

但我抓住断言。 文件名2: enter image description here

不同位:[29]

为什么?

1 个答案:

答案 0 :(得分:7)

57216似乎属于代理对范围,在UTF-16中用于编码非BMP代码点。它们需要成对出现,否则解码将无法为您提供正确的代码点。

65533是解码器给出的特殊错误字符,因为缺少其他代理。

换句话说:原始字符串不是UTF-16字符串。

More info on Wikipedia

相关问题