我想从二进制文件中读取无符号字节。 于是我写了如下代码。
#include <iostream>
#include <fstream>
#include <vector>
#include <istream>
std::string filename("file");
size_t bytesAvailable = 128;
size_t toRead = 128;
std::basic_ifstream<unsigned char> inf(filename.c_str(), std::ios_base::in | std::ios_base::binary) ;
if (inF.good())
{
std::vector<unsigned char> mDataBuffer;
mDataBuffer.resize(bytesAvailable) ;
inF.read(&mDataBuffer[0], toRead) ;
size_t counted = inF.gcount() ;
}
这将导致读取始终为 0 字节,如变量 counted 所示。
网上似乎有引用资料说我需要设置语言环境才能使这项工作。我不清楚如何做到这一点。
相同的代码使用数据类型“char”而不是“unsigned char”
上面使用 unsigned char 的代码似乎可以在 Windows 上运行,但在 colinux Fedora 2.6.22.18 中运行失败。
我需要做什么才能让它在 linux 上工作?
最佳答案
C++ 确实只需要实现为两个版本的字符特征提供明确的特化:
std::char_traits<char>
std::char_traits<wchar_t>
流和字符串使用这些特征来计算各种事物,例如 EOF 值、字符范围的比较、将字符扩展为 int 等等。
如果你像这样实例化一个流
std::basic_ifstream<unsigned char>
您必须确保流可以使用相应的字符特征特化,并且该特化确实有用。此外,流使用构面来进行数字的实际格式化和读取。同样,您必须手动提供这些特化。该标准甚至不要求实现具有主模板的完整定义。所以你也可能会得到一个编译错误:
error: specialization std::char_traits could not be instantiated.
我会使用 ifstream
而是(这是一个 basic_ifstream<char>
)然后去读入一个 vector<char>
.在解释 vector 中的数据时,仍然可以将它们转换为 unsigned char
之后。
关于C++从文件流中读取无符号字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/604431/