这里有两段代码,我起初认为应该是等价的:
{
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";
}
Run Code Online (Sandbox Code Playgroud)
我的问题是第一个版本输出153(可能取决于输入数据)而第二个输出128(这是我所期望的).这必须与第一个版本中的数据提取方式有关,但我不明白为什么它不起作用.不应该只是打电话:
istream& operator>> (istream& is, unsigned char& ch);
Run Code Online (Sandbox Code Playgroud)
并每次移动文件一个字节?