MinGW C++:读取具有非 ascii 文件名的文件

MinGW C++: Reading a file with non-ascii file name

简单任务:我想读取一个文件名不是 ascii 的文件。

在 linux 和 MacOS 上,我只是将文件名作为 UTF-8 编码字符串传递给 fstream 构造函数。在 windows 这失败了。

正如我从 this question 了解到的,windows 根本不支持 utf-8 文件名。但是,它提供了一个自己的非标准 open 方法,该方法采用 utf-16 wchar_t*。因此,我可以简单地将我的 string 转换为 utf-16 wstring 并且没问题。但是,在 MinGW 标准库中,fstreamwchar_t* open 方法根本不存在。

那么,如何在 MinGW 上打开非 ascii 文件名?

我以前也遇到过同样的问题。不幸的是,在您可以使用 std::filesystem::path 之前,您需要以某种方式解决这个问题,例如通过包装所有东西,例如就像我做的 here,这使得 "user code" 看起来像这样:

auto stream_ptr = open_ifstream(file_name); // I used UTF-8 and converted to UTF-16 on Windows as in the code linked above
auto& stream = *stream_ptr;
if(!stream)
    throw error("Failed to open file: \'" + filename + "\'.");

丑陋是的,有点便携,是的。请注意,这在 Windows 上的 Libc++ 上不起作用,尽管该组合目前无论如何都不起作用,这无关紧要。

您可能可以给予 Boost.Nowide a try. It has a fstream wrapper which will convert your string to UTF-16 automatically. It is not yet in boost, but already in the review schedule(希望很快成为一部分)。我从来没有用 mingw 尝试过,但玩过 visual studio 并发现它退出整洁。