Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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)

>Solution :

<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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading