1

I am writing C++ in MSVC for Windows. I need to use std::wifstream instead std::ifstream so that I can open files with "Windows Unicode" (i.e., wchar_t[]) path.

However, this class has only one binary reading method, that is:

std::wistream& read (wchar_t* s, streamsize n);

So how can I read a single byte/char with this class?

Update with solutions:

Thank you all for your suggestions, I didn't know that ifstream constructors accept wchar_t[] as file name. Based on your information, I came up with 2 solutions that works:

  1. std::ifstream file(L"...");
  2. std::ifstream file(std::filesystem::path(L"..."));

Solution 1 would be more prefered as solution 2 only works under c++20;

kien
  • 197
  • 9
  • 2
    `I need to use std::wifstream instead std::ifstream so that I can open files with "Windows Unicode" (i.e., wchar_t[]) path.` No. `So how can I read a single byte/char with this class?` You can't, because `wifstream` reads `wchar_t`s, thats its purpose. – tkausl Oct 02 '21 at 01:37
  • 1
    If you want to read a single character (a `wchar_t` in this case) use the `get` member function. Use the overload that takes a single `wchar_t` by `ref`. – WBuck Oct 02 '21 at 01:41
  • 3
    Unicode path and `wchar_t` content are two different things. In MSVC both `ifstream` and `wifstream` support `wchar_t*` file names. You want `ifstream`. – n. m. could be an AI Oct 02 '21 at 01:46
  • @WBuck They want to read a single _byte_, not _character_. – Etienne de Martel Oct 02 '21 at 01:49
  • I'd have to agree with @n.1.8e9-where's-my-sharem., use an `std::ifstream` it's almost certainly what you want. If, after reading in the file you want an `std::wstring` instead of an `std::string` for passing to `Win32` API functions you can convert it with `MultiByteToWideChar` – WBuck Oct 02 '21 at 01:51
  • @EtiennedeMartel I think he's confused to be honest, as that doesn't make sense for `UTF16`. – WBuck Oct 02 '21 at 01:52
  • @WBuck Why wouldn't it make sense to want to read binary files on Windows, where paths are Unicode? – Etienne de Martel Oct 02 '21 at 01:56
  • @EtiennedeMartel Let's be clear here, he doesn't want to read `bytes` he wants to read a single `byte`. I'd be curious what information can be gleaned from reading a single `byte` in his particular scenario? – WBuck Oct 02 '21 at 02:21
  • 1
    You can use `std::ifstream fin(L"UTF16_path_name.txt")` and the file content can be UTF8 or ASCII – Barmak Shemirani Oct 02 '21 at 05:29

0 Answers0