Windows 非 ASCII 文件路径

Windows non-ASCII file paths

本文关键字:路径 文件 ASCII Windows      更新时间:2023-10-16

我正在做一些实验来更好地了解转换,并且有以下代码无法按预期工作

std::wstring inScriptPath = "non-ASCII file name"
using convert_type = std::codecvt_utf8_utf16<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;
std::string my_path = converter.to_bytes(inScriptPath);
std::fstream myfile;
myfile.open(my_path.c_str(), ios::in); //open the file
if (myfile.is_open()) {
std::cout << "Openning file for reading with fstream" << std::endl;
myfile.close();
}

FILE * pFile;
pFile = fopen(my_path.c_str(), "r");
if (pFile != NULL)
{
std::cout << "Openning file for reading with fopen" << std::endl;       
fclose(pFile);
}

我预计在将 wstring 转换为字符串文件后打开/fopen 应该可以工作,但它不起作用。 我做错了什么?

charwchar_t是不兼容的。 您不能在C++级别自动转换,您必须使用诸如WideCharToMultiByte之类的函数。

只需忘记Windows中的8位字符串即可。始终使用Unicode,std::wstringwchar_twfopen等。Windows 内部使用 16 位宽字符。UTF-8 不会自动转换。