Stas Badzi
Stas Badzi

Reputation: 748

Is there a way to create a fstream, ifstream or ofstream object with a wchar_t* or wstring filename? (c++)

I am tring to compile some code wrote for the msvc compiler with msys2 gcc (msys2-msys2 not msys2-mingw) and it contains

wstring filename;
ifstream file(filename);

I tried to find a way to use _wfopen() witch I can import from msvcrt.dll but I couldn't find a way to override the underlying __basic_file type which contains a FILE*

I also tried defining

#define _GLIBCXX_HAVE__WFOPEN 1
#define _GLIBCXX_USE_WCHAR_T 1 

but that lead to linkage errors (here)

I also tried exporting a function create_ifstream(const wchar_t*) from mingw-w64 gcc, but ifstream doesn't have a copy constructor so it either lead to compiler errors or to a segmaentation fault at runtime

Does anybody know how I could open a file with a wide character name (It's windows so converting the file name to UTF-8 won't work with some filenames)

Upvotes: 6

Views: 91

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38863

<filesystem> can do that.

#include <filesystem>
#include <fstream>
#include <string>

namespace fs = std::filesystem;

int main() {
  std::wstring some_path;
  std::ifstream file1{fs::path(some_path)};
  std::ifstream file2{fs::path(L"some_path")};
}

https://godbolt.org/z/h14eGrErz - gcc and msvc.

Upvotes: 9

Related Questions