Search code examples
c++gccclang

bad std::wstring support inside <fstream>?


It looks like the std::wstring support in the standard library for gcc/clang is kind of poor. Or am I doing something wrong here:

#include <fstream>
#include <string>

int main()
{
    std::string a;
    std::ifstream ifs(a); // fine

    std::wstring b;
    std::ifstream ifs2(b); // compilation error gcc/clang

    return 0;
}

I tested this on godbolt and it basically only compiles under windows.

Do you know if this is by design? Are there any compiler switches I could use so that it will work?

Edit: Thanks for the suggestions. It confirmed me that I solved my original problem good enough and I learned also a few new things.


Solution

  • Standard C++ file streams do not accept std::wstring for the filename.

    In standard C++17 and later (and in MSVC in earlier versions), file streams do accept const wchar_t* for the filename, but only on Windows where std::filesystem::path::value_type is wchar_t:

    #include <fstream>
    #include <string>
    
    int main()
    {
        std::wstring b = ...;
        //std::ifstream ifs(b); // compilation error
        std::ifstream ifs(b.c_str()); // fine, but only on Windows
    
        return 0;
    }
    

    Alternatively, in standard C++17 and later, you can open a file stream using a std::filesystem::path instead, which can be created from a std::wstring filename:

    #include <fstream>
    #include <string>
    #include <filesystem>
    
    int main()
    {
        std::wstring b = ...;
        std::filesystem::path p(b);
        std::ifstream ifs(p);
    
        return 0;
    }