How to use std::ifstream to read in a binary file with a wide string path

元气小坏坏 提交于 2019-12-19 05:19:18

问题


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 binary, 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);
  ...
}

回答1:


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.



来源:https://stackoverflow.com/questions/5382451/how-to-use-stdifstream-to-read-in-a-binary-file-with-a-wide-string-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!