办不到!!!

windows只接受8bit的ANSI或者UTF16编码的文件名,你可以在代码里面使用utf8编码的文件名,但是当你打开文件时,你必须将其转化为8bit的ANSI或者UTF16编码的文件名。
幸运的是,VC++的std::ifstream 跟 std::ofstream对标准做了扩展,他们的构造函数跟open()方法可以接受wchat_t*的字符串(utf16编码的)。

下面提供一种基于VC++的扩展的兼容windows的方案:

#ifdef _MSC_VER
std::wstring ToUtf16(std::string str)
{
    std::wstring ret;
    int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), NULL, 0);
    if (len > 0)
    {
        ret.resize(len);
        MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), &ret[0], len);
    }
    return ret;
}
#endif

int main()
{
    std::string utf8path = ...;
    std::ifstream iFileStream(
        #ifdef _MSC_VER
        ToUtf16(utf8path).c_str()
        #else
        utf8path.c_str()
        #endif
        , std::ifstream::in | std::ifstream::binary);
    ...
    return 0;
}
posted on 2020-02-22 11:21  ConfuciusPei  阅读(502)  评论(0编辑  收藏  举报