以下是我最初认为应该等效的两个代码片段:
{
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);
并每次将filepos移动一个字节?