c++windowsunicodemingwfstream

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.

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?


Solution

  • I struggled with the same issue before. Unfortunately, until you can use std::filesystem::path, you need to work around this in some way, e.g. by wrapping everything, e.g. 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.