0

I'm trying to read a file with ifstream:

std::ifstream is("sample_freeway.h264", std::ifstream::binary);

std::cout << "reading" << std::endl;
if (is)
{
    while (!is.eof() || !is.fail() || !is.bad())
    {
        auto buffer = std::make_shared<SimpleEncodedPacket>();
        is.read(reinterpret_cast<char *>(buffer->getFramePointer()), buffer->getSize());
    }
    std::cout << std::endl;
} else {
    std::cout << "could not open file" << std::endl;
}

but the while keeps going forever, even though the file is super small. It should finish almost instantly. What am I doing wrong?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 4
    Your `while` loop will run so long as at least **one** of the conditions is met. You probably mean `&&` instead of `||`. – Adrian Mole Jul 25 '20 at 19:37
  • Please take some to read [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Some programmer dude Jul 25 '20 at 19:40
  • 2
    Adrian Mole has it right. De Morgans law is your friend: ``!(a | b | c) == !a && !b && !c`` – BitTickler Jul 25 '20 at 19:41

2 Answers2

3

Change

while (!is.eof() || !is.fail() || !is.bad())

to

while (!is.eof() && !is.fail() && !is.bad())

as said Adrian Mole.

Or even better, use is.good() (thanks BitTickler)

Ihor Drachuk
  • 1,265
  • 7
  • 17
2

As Adrian Mole pointed out, you got the boolean expression wrong. But this is actually so common, that there is another "goodie" hidden in std::ios:

See for example the reference on cplusplus.com:

std::ios::good bool good() const; Check whether state of stream is good Returns true if none of the stream's error state flags (eofbit, failbit and badbit) is set.

Had you used this function, you would not have been able to make the mistake you made.

    ...
    while( is.good() ) {
        ...
    }
    ...
BitTickler
  • 10,905
  • 5
  • 32
  • 53