True on both points, but nonetheless it is a fairly common practice and generally safe to do on most systems. That said, there are plenty of C++ tricks that be used to achieve a portable solution with minimal effort:
Code:
#include <iostream>
#include <fstream>
#include <stdexcept>
struct read_binary_file_helper
{
read_binary_file_helper( std::istream& in )
: in( in )
{ }
template < typename Type >
bool operator ( ) ( Type& value, bool throw_on_error = true )
{
if( in.read( ( char* )&value, sizeof( value ) ) )
return true;
if( throw_on_error )
throw std::runtime_error( "read_binary_file_helper: file read error" );
return false;
}
template < typename Type >
inline operator Type ( void )
{
Type
value;
( *this )( value );
return value;
}
std::istream&
in;
};
struct BitmapFileHeader {
unsigned short Type;
unsigned int Size;
unsigned short Reserved1;
unsigned short Reserved2;
unsigned int OffBits;
};
struct BitmapInfoHeader {
unsigned int Size;
long Width;
long Height;
unsigned short Planes;
unsigned short BitCount;
unsigned int Compression;
unsigned int SizeImage;
long XPelsPerMeter;
long YPelsPerMeter;
unsigned int ClrUsed;
unsigned int ClrImrportant;
};
template < typename Type >
void print( char const* text, Type const& value )
{
std::cout << text << ": " << std::hex << "0x" << value << std::endl;
}
int main( int, char** argv )
{
using namespace
std;
while( *( ++argv ) )
{
cout << "File: '" << *argv << "'" << endl;
try
{
ifstream
in( *argv, ios::binary );
if( !in )
throw std::runtime_error( "cannot open file" );
BitmapFileHeader
bfh;
BitmapInfoHeader
bih;
read_binary_file_helper
rbh( in );
print( "bfh.Type", bfh.Type = rbh );
print( "bfh.Size", bfh.Size = rbh );
print( "bfh.Reserved1", bfh.Reserved1 = rbh );
print( "bfh.Reserved2", bfh.Reserved2 = rbh );
print( "bfh.OffBits", bfh.OffBits = rbh );
print( "bih.Size", bih.Size = rbh );
print( "bih.Width", bih.Width = rbh );
print( "bih.Height", bih.Height = rbh );
print( "bih.Planes", bih.Planes = rbh );
print( "bih.BitCount", bih.BitCount = rbh );
print( "bih.Compression", bih.Compression = rbh );
print( "bih.SizeImage", bih.SizeImage = rbh );
print( "bih.XPelsPerMeter", bih.XPelsPerMeter = rbh );
print( "bih.YPelsPerMeter", bih.YPelsPerMeter = rbh );
print( "bih.ClrUsed", bih.ClrUsed = rbh );
print( "bih.ClrImrportant", bih.ClrImrportant = rbh );
}
catch( exception const& error )
{
cerr << "Error: " << error.what( ) << endl;
}
}
return 0;
}
Isn't C++ great?