c++eof和故障位在读取二进制文件的过程中

c++ eof and failbit in the middle of reading binary file

本文关键字:二进制文件 过程中 读取 故障 c++eof      更新时间:2023-10-16

我在读取二进制文件时遇到问题。它似乎没有读到尽头:

// get file size
ifs.open (inFile.c_str(), ios::binary | ios::ate);
cout << "file size:  " << ifs.tellg() << endl;;
ifs.close();
// read file
ifs.open (inFile.c_str(), ios::in | ios::binary);
int counter = 0;
char c = 0;
for (counter = 0; ifs; ++counter)
    ifs >> c;
cout << "last char:  " << int(c) << endl;
cout << "read bytes: " << counter << endl;
cout << "fail? " << (ifs.fail() ? "yes" : "no") << endl;
cout << "bad?  " << (ifs.bad() ? "yes" : "no") << endl;
cout << "eof?  " << (ifs.eof() ? "yes" : "no") << endl;
ifs.close();

以下是输出。我不明白为什么我在文件中间得到eofbit,以及为什么它与failbit:一起出现

file size:  289384
last char:  1
read bytes: 288598
fail? yes
bad?  no
eof?  yes

我在Unix系统上得到了这一点

我做了一个测试,发现了问题。一旦将ofs << c添加到for循环中,就很明显了。

它不是在读空白。

您可以通过添加#include <iomanip>ifs >> noskipws或使用二进制输入函数(如ifs.get(c) )来修复此问题