void OpenUtf8FStreamForRead(std::fstream &aFStream, const char *aUtf8FileName) { // Unfortunately the windows C++ STL library will not open files specified via a UTF-8 filename. // The workaround is to convert the UTF-8 name to the short DOS compatible name and open that instead // First convert the UTF-8 name to UTF-16 for use with the windows APIs WCHAR *utf16Name = WindowsUtf8ToUtf16(aUtf8FileName); // Obtain short DOS compatible name for file WCHAR *utf16NameDos = WindowsRetrieveDosName(utf16Name); if(utf16NameDos == 0) { aFStream.setstate(std::ios_base::badbit); delete [] utf16Name; return; } char *utf8NameDos = WindowsUtf16ToUtf8(utf16NameDos); aFStream.open(utf8NameDos, std::ios_base::binary | std::ios_base::in); delete [] utf8NameDos; delete [] utf16NameDos; delete [] utf16Name; return; }
void OpenUtf8FStreamForWrite(std::fstream &aFStream, const char *aUtf8FileName) { // Unfortunately the windows C++ STL library will not open files specified via a UTF-8 filename. // The workaround is to make sure the file already exists and then convert the UTF-8 name to the short DOS compatible name // and open that instead // First convert the UTF-8 name to UTF-16 for use with the windows APIs WCHAR *utf16Name = WindowsUtf8ToUtf16(aUtf8FileName); // Make sure the file exists HANDLE fh = CreateFileW((WCHAR *)utf16Name, GENERIC_WRITE, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 ); if(fh == INVALID_HANDLE_VALUE) { dbg << Log::Indent() << "Failed to create file '" << aUtf8FileName << "'" << Log::Endl(); aFStream.setstate(std::ios_base::badbit); delete [] utf16Name; return; } // Close handle CloseHandle(fh); // Obtain short DOS compatible name for file WCHAR *utf16NameDos = WindowsRetrieveDosName(utf16Name); if(utf16NameDos == 0) { aFStream.setstate(std::ios_base::badbit); delete [] utf16Name; return; } char *utf8NameDos = WindowsUtf16ToUtf8(utf16NameDos); aFStream.open(utf8NameDos, std::ios_base::binary | std::ios_base::trunc | std::ios_base::out); delete [] utf8NameDos; delete [] utf16NameDos; delete [] utf16Name; return; }