Is it possible to read data from a binary file to a C++ class using istream::read
? I know it can be done for structures, but I couldnt do it for a class.
[Edit]
Want code?
#include <iostream>
#include <fstream>
class BITMAPFILEHEADER
{
private:
char type[ 2 ]; // Magic identifier
unsigned int size; // File size in bytes
unsigned short int reserved1; // Reserved; always zero
unsigned short int reserved2; // Reserved; always zero
unsigned int offset; // Offset to image data, bytes
public:
friend std::istream& operator>>(std::istream& s, BITMAPFILEHEADER& r);
};
std::istream& operator>>(std::istream& s, BITMAPFILEHEADER& r);
std::istream& operator>>(std::istream& s, BITMAPFILEHEADER& r)
{
#if 0
// This does not work
s.read( reinterpret_cast <char*>(&r), sizeof(BITMAPFILEHEADER) );
if( s.bad() )
{
std::cerr << "Error reading data" << std::endl;
exit( 0 );
}
#endif
#if 1
// This works
s.read( r.type, 2 * sizeof(char) );
if( s.bad() )
{
std::cerr << "Error reading data" << std::endl;
exit( 0 );
}
s.read( (char*)&(r.size), sizeof(unsigned int) );
if( s.bad() )
{
std::cerr << "Error reading data" << std::endl;
exit( 0 );
}
s.read( (char*)&(r.reserved1), sizeof(unsigned short int) );
if( s.bad() )
{
std::cerr << "Error reading data" << std::endl;
exit( 0 );
}
s.read( (char*)&(r.reserved2), sizeof(unsigned short int) );
if( s.bad() )
{
std::cerr << "Error reading data" << std::endl;
exit( 0 );
}
s.read( (char*)&(r.offset), sizeof(unsigned int) );
if( s.bad() )
{
std::cerr << "Error reading data" << std::endl;
exit( 0 );
}
#endif
return s;
}