Last active
August 30, 2016 12:38
-
-
Save skogorev/e8dc41d5958a52054815d3a70d1fb518 to your computer and use it in GitHub Desktop.
Checking wrong UTF-16 names in Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <string> | |
#include <Windows.h> | |
std::string utf16ToUtf8(const std::wstring& utf16) { | |
int size = WideCharToMultiByte(CP_UTF8, 0, utf16.data(), static_cast<int>(utf16.size()), NULL, 0, NULL, NULL); | |
std::string utf8(size, 0x00); | |
WideCharToMultiByte(CP_UTF8, 0, utf16.data(), static_cast<int>(utf16.size()), &utf8[0], size, NULL, NULL); | |
return utf8; | |
} | |
std::wstring utf8ToUtf16(const std::string& utf8) { | |
int size = MultiByteToWideChar(CP_UTF8, 0, utf8.data(), static_cast<int>(utf8.size()), NULL, 0); | |
std::wstring utf16(size, 0x00); | |
MultiByteToWideChar(CP_UTF8, 0, utf8.data(), static_cast<int>(utf8.size()), &utf16[0], size); | |
return utf16; | |
} | |
int main() { | |
std::wstring original_utf16 = { 0xDCA9, 0x2E, 0x74, 0x78, 0x74, 0x00 }; | |
// Creating the file with non-valid surrogate pair | |
HANDLE handle = CreateFileW(original_utf16.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); | |
if (handle == INVALID_HANDLE_VALUE) { | |
return 1; | |
} | |
CloseHandle(handle); | |
// Converting to UTF-8 and back | |
std::string utf8 = utf16ToUtf8(original_utf16); | |
std::wstring utf16 = utf8ToUtf16(utf8); | |
// Trying to open the file | |
handle = CreateFileW(utf16.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); | |
if (handle == INVALID_HANDLE_VALUE) { | |
assert(original_utf16 == utf16); | |
return 1; // Will here | |
} | |
CloseHandle(handle); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment