gexicide
gexicide

Reputation: 40048

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?

Upvotes: 3

Views: 1523

Answers (3)

Mikhail Izhevsk
Mikhail Izhevsk

Reputation: 1

I'v solved the problem by converting UTF8 std::string to std::filesystem::path and then send it to the std::ifstream constructor (Windows 10, MSYS2, GCC, C++17):

std::filesystem::path xpath(file_name);
std::ifstream xstream(xpath);

Works fine with non-ASCII characters in file_name string.

Upvotes: 0

user1810087
user1810087

Reputation: 5334

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.

Upvotes: 1

rubenvb
rubenvb

Reputation: 76519

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.

Upvotes: 1

Related Questions