这里有两个代码片段,我最初认为它们应该是等效的:
{
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);并每次移动文件头一个字节?
发布于 2012-05-29 15:49:47
如果你阅读operator>>的描述(例如here),那么你会看到它在阅读之前跳过了空格,直到它再次命中空格。空格不仅是空格(0x20),还包括制表符(0x09)和换行符(0x0a)。
因此,如果您的二进制数据包含被视为文本文件空白的字节,那么operator>>将读取这些字节,但不会存储它们,这将扭曲tellg报告的数字。
发布于 2012-05-29 15:50:44
当您以二进制格式打开一个流时,使用operator>>并不是一个好主意。
我假设在您的示例中,流中包含某种空白字符(例如0x20)。
您可以使用skipws修饰符,也可以读取这些内容。
https://stackoverflow.com/questions/10794820
复制相似问题