How to use std::ifstream to read in a binary file with a wide string path
I am reading a binary file as:
const size_t stBuffer = 256;
char buffer[stBuffer];
std::wstring wPath(L"blah");
std::wifstream ifs(wPath.c_str(), std::wifstream::in | std::wifstream::binary)
while (ifs.good())
{
ifs.read(buffer, sizeof(buffer));
...
}
But I am realizing this is not a true binary read. The ifstream actually reads a byte and converts it to a wide char. So if the binary file has the content 0x112233...ff
, I actually read 0x110022003300...ff00
.
This doesn't make much sense to me: first, I only need to use a wide fstream because the file name is non Latin. Second, if I say the fstream is binar开发者_如何学JAVAy, why does read
read wide chars? The code below does what I want. Is there a way to achieve that using std fstreams?
FILE* ifs = _wfopen(L"blah", L"rb");
while (!feof(ifs))
{
size_t numBytesRead = fread(buffer, 1, sizeof(buffer), ifs);
...
}
The current C++ standard doesn't provide wide char paths. Even the wchar_t version receives a regular const char* filename. You already used a compiler extension, so continue using this extension with a normal ifstream:
std::wstring wPath(L"blah");
std::ifstream ifs(wPath.c_str(), std::ios::in | std::ios::binary)
EDIT: consider using utf-8 strings instead of wide strings and use Boost.Nowide (not yet in boost) to open files.
EDIT: Boost.Nowide was accepted in boost. Also Windows 10 added support for UTF-8 in its narrow-string API, which can be enabled through a manifest. This makes all the wide-char interfaces pretty much unportable and redundant.
精彩评论