Simple task: I want to read a file which has a non-ascii file name.
On linux and MacOS, I simply pass the file name as a UTF-8 encoded string to the fstream
constructor. On windows this fails.
As I learned from this question , windows simply does not support utf-8 filenames. However, it provides an own non-standard open
method that takes a utf-16 wchar_t*
. Thus, I could simply convert my string
to utf-16 wstring
and be fine. However, in the MinGW standard library, that wchar_t* open
method of fstream
simply does not exist.
So, how can I open a non-ascii file name on MinGW?
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:
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.
You probably can give 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 (and hopefully soon part of boost). I never tried it with mingw but played around with visual studio and found it quit neat.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.