4

Create a file and fill it up with zeroes:

dd if=/dev/zero of=/tmp/zeroes count=1

Write this little program to extract the first unsigned integer it encounters in the file.

#include <assert.h>
#include <fstream>

int main()
{
    std::ifstream reader( "/tmp/zeroes", std::ios_base::binary );
    uint32_t number;
    reader >> number;

    assert( !reader.fail() );
}

Why is the assert triggered?

qdii
  • 12,505
  • 10
  • 59
  • 116
  • 4
    Even if you set the stream mode to binary, `>>` to an integer type is a formatted input function (uses `num_get` which expects a text representation). – dyp Apr 10 '14 at 12:27

1 Answers1

8

Because /dev/zero delivers binary zeros, not the character '0', and >> does (or tries to do) a conversion from text.

James Kanze
  • 150,581
  • 18
  • 184
  • 329