I learned how to read binary files in C++ today. My function (which creates an MD5 hash of a file) ended up looking a little different to the example that I learned from:
const int BUFFER_SIZE = 1024; int length; char buffer[ BUFFER_SIZE ]; MD5_CTX ctx; MD5Init( &ctx ); ifstream is( path.c_str(), ios::binary ); while ( is.good() ) { is.read( (char *)buffer, BUFFER_SIZE ); streamsize count = is.gcount(); MD5Update( &ctx, (unsigned char *)buffer, count ); } if ( is.eof() ) { // it's ok, we're at the end of the file } else if ( is.bad() ) { // bad bit is set cout << "Bad bit is set while reading '" << path << "'." << endl; cout << strerror( errno ) << endl; exit ( 1 ); } else if ( is.fail() ) { cout << "Fail bit is set while reading '" << path << "'." << endl; cout << strerror( errno ) << endl; exit( 1 ); } is.close();