Click to See Complete Forum and Search --> : reading into a class like a struct


psycorpse
February 24th, 2008, 01:04 PM
I am pretty novice when it comes to C++ however I have take the basic courses at the community college as well as oo programming with C++. I am trying to write something that has been written about 3 million times. I am writing a class to read to BITMAP file. I am using some c source code to help me with what I need to do to read these files. My question is this:

How do you read x amount of data into a class and it sets the variables like with a struct? or does it automatically do this?

typedef struct /**** BMP file header structure ****/
{
unsigned short bfType; /* Magic number for file */
unsigned int bfSize; /* Size of file */
unsigned short bfReserved1; /* Reserved */
unsigned short bfReserved2; /* ... */
unsigned int bfOffBits; /* Offset to bitmap data */
} BITMAPFILEHEADER;

fread(&header, 1, sizeof(BITMAPFILEHEADER), filepointer);

This will set all the variables in the struct. I am looking to do this with classes... Is it possible? Also instead of using stdio.h I will be doing this <fstream>. Would that be the best way as well?

Any help would be greatly appreciated.

Thanks
Mike

Lindley
February 24th, 2008, 01:22 PM
It works in the struct case because the bytes in the file correspond to "ushort, uint, ushort, ushort, uint", and the struct's layout in memory is (probably) the same.

It's dangerous to make such assumptions; it's even more dangerous to do it with classes, when things like inheritance could potentially make fields not fall in memory quite where you expect them to.

The simplest safe way to do it would be as, in the above case:

fread(&header.bfType, 1, sizeof(unsigned short), filepointer);
fread(&header.bfSize, 1, sizeof(unsigned int), filepointer);
etc.

In the case of fread, it will probably do some buffering for you; to avoid that assumption, you could simply read 14 bytes to a char[14] buffer of your own using fread and then transfer them to the fields from your buffer. The point is you want to physically hit the disk as few times as possible, because this is very slow.

I'm not terribly familiar with fstream, but you want to make sure it doesn't try to do formatted IO. There must be a way to make it do binary IO instead.....

Paul McKenzie
February 24th, 2008, 01:57 PM
How do you read x amount of data into a class and it sets the variables like with a struct?First, you should realize that there is no difference between a struct and a class except for default member visibility:

http://www.parashift.com/c++-faq-lite/classes-and-objects.html#faq-7.8

There is a very quick answer to your question:

class BitmapReader
{
private:
BITMAPFILEHEADER m_bmHeader;
//...
public:
void ReadBitmap(); // this fills in the m_bmHeader.
};

So you don't need to change anything -- just declare a member of type BITMAPFILEHEADER and read into that just like you're doing now.

Regards,

Paul McKenzie