istream::read 和 istream::operator 之间的区别>>
Difference between istream::read and istream::operator>>
这里有两个代码片段,我最初认为它们应该是等效的:
{
std::ifstream stream("test.bin", std::ios_base::in | std::ios_base::binary);
unsigned char count = 128;
unsigned char read = 0;
unsigned char scanline[128];
long long start = stream.tellg();
while (count--) {
stream >> scanline[read++]; // <---- This is the only line which differs
}
long long end = stream.tellg();
std::cout << end - start << "n";
}
{
std::ifstream stream("test.bin", std::ios_base::in | std::ios_base::binary);
unsigned char count = 128;
unsigned char read = 0;
unsigned char scanline[128];
long long start = stream.tellg();
while (count--) {
stream.read((char*)&scanline[read++], 1); // <---- This is the only line which differs
}
long long end = stream.tellg();
std::cout << end - start << "n";
}
我的问题是第一个版本输出 153(可能取决于输入数据),第二个版本输出 128(这是我预期的)。这一定与第一个版本中的数据提取方式有关,但我不明白为什么它不起作用。它不应该只是调用:
istream& operator>> (istream& is, unsigned char& ch);
并且每次移动文件一个字节?
如果您阅读operator>>
的描述(例如这里),那么您会看到它在阅读之前跳过空格,直到再次遇到空格。空格不仅是空格(0x20
),还包括制表符(0x09
)和换行符(0x0a
)。
因此,如果您的二进制数据包含被视为文本文件的空格的字节,那么operator>>
将读取但不存储它们,这将扭曲 tellg
报告的数字。
在
二进制中打开流时使用该operator>>
不是一个好主意。
我假设在您的情况下,您的流中有某种空格字符(例如0x20)。
您可以使用 skipws
修饰符来读取这些内容。
相关文章:
- 为什么istream不支持右值提取
- 将无符号char*转换为std::istream*C++
- 需要从 istream 和 ostream 派生 iostream
- 使用std::istream::peek()总是安全的吗
- EASTL矢量<向量<int>>连续的
- 使用 istream 参数读取的 istream 函数
- istream std::cin如何修改自定义istream缓冲区
- 为什么我在使用 istream 迭代器时会出现 seg 错误?
- 在清除 istream 之前,我不应该需要取消获取它吗?
- C++,如何根据运行时条件构造引用不同 istream 对象的对象?
- 如何将QByteArray转换为std::istream或std::ifstream?
- 逗号在重载 ostream 和 istream 在结构中分开
- 为什么 Clang std::ostream 写一个 std::istream 无法读取的双精度?
- 从函数返回 istream 的正确方法
- 阅读从 istream 到矢量的不同类型列表
- 关于 istream 中的错误处理的问题
- C++ 模板类无法修复 ostream 和 istream 函数
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- iStream 运算符跳过空格字符
- 如何在 c++ 中将 IStream 转换为 Base64 字符串