![](/img/trans.png)
[英]Is it better to read an entire file in std::string or to manipulate a file with std::ifstream?
[英]How to use std::ifstream to read in a binary file with a wide string path
我正在阅读一个二进制文件:
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));
...
}
但我意识到这不是真正的二进制读取。 ifstream 实际上读取一个字节并将其转换为宽字符。 因此,如果二进制文件的内容为0x112233...ff
,我实际上读取的是0x110022003300...ff00
。
这对我来说没有多大意义:首先,我只需要使用宽 fstream,因为文件名不是拉丁文。 其次,如果我说 fstream 是二进制的,为什么read
读取宽字符? 下面的代码做我想要的。 有没有办法使用 std fstreams 实现这一目标?
FILE* ifs = _wfopen(L"blah", L"rb");
while (!feof(ifs))
{
size_t numBytesRead = fread(buffer, 1, sizeof(buffer), ifs);
...
}
当前的 C++ 标准不提供宽字符路径。 甚至 wchar_t 版本也会收到一个常规的 const char* 文件名。 你已经使用了一个编译器扩展,所以继续使用这个扩展和一个普通的 ifstream:
std::wstring wPath(L"blah");
std::ifstream ifs(wPath.c_str(), std::ios::in | std::ios::binary)
编辑:考虑使用 utf-8 字符串而不是宽字符串并使用Boost.Nowide (尚未在 boost 中)打开文件。
编辑: Boost.Nowide 在 boost 中被接受。 此外,Windows 10 在其窄字符串 API 中添加了对 UTF-8 的支持,可以通过清单启用。 这使得所有宽字符接口几乎不可移植和冗余。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.