[英]MinGW C++: Reading a file with non-ascii file name
Simple task: I want to read a file which has a non-ascii file name. 简单任务:我想读取一个具有非ascii文件名的文件。
On linux and MacOS, I simply pass the file name as a UTF-8 encoded string to the fstream
constructor. 在linux和MacOS上,我只是将文件名作为UTF-8编码的字符串传递给
fstream
构造函数。 On windows this fails. 在Windows上,这失败了。
As I learned from this question , windows simply does not support utf-8 filenames. 正如我从这个问题中学到的,windows根本不支持utf-8文件名。 However, it provides an own non-standard
open
method that takes a utf-16 wchar_t*
. 但是,它提供了一个自己的非标准
open
方法,它采用utf-16 wchar_t*
。 Thus, I could simply convert my string
to utf-16 wstring
and be fine. 因此,我可以简单地将我的
string
转换为utf-16 wstring
并且没问题。 However, in the MinGW standard library, that wchar_t* open
method of fstream
simply does not exist. 但是,在MinGW标准库中,
fstream
wchar_t* open
方法根本不存在。
So, how can I open a non-ascii file name on MinGW? 那么,如何在MinGW上打开非ascii文件名?
I struggled with the same issue before. 我以前在同一个问题上挣扎过。 Unfortunately, until you can use
std::filesystem::path
, you need to work around this in some way, eg by wrapping everything, eg like I did here , which makes "user code" look like this: 不幸的是,在你可以使用
std::filesystem::path
,你需要以某种方式解决这个问题,例如通过包装所有内容,例如我在这里做的,这使得“用户代码”看起来像这样:
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 + "\'.");
Ugly yes, slightly portable, yes. 丑陋的,有点便携,是的。 Note this does not work on Libc++ on Windows, although that combination is currently not functioning anyways that doesn't matter much.
请注意,这对Windows上的Libc ++不起作用,尽管这种组合目前无法正常运行并不重要。
You probably can give Boost.Nowide a try. 你可能会试试Boost.Nowide 。 It has a
fstream
wrapper which will convert your string to UTF-16 automatically. 它有一个
fstream
包装器,可以自动将你的字符串转换为UTF-16。 It is not yet in boost, but already in the review schedule (and hopefully soon part of boost). 它还没有提升,但已经在审查时间表中 (并且很快就会提升一部分)。 I never tried it with mingw but played around with visual studio and found it quit neat.
我从来没有和mingw一起尝试过,但是在视觉工作室玩弄它并且发现它整洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.