I need to do something like this:

ifstream infile(Filename.c_str());
//ifstream infile(Filename.c_str(), ios::binary);
string line;

///////////// Read Header ////////////
//read magic number
getline(infine, line);
	
while(line[0] == "#")
	getline(infile, line);
MagicNumber_ = line;

//more ascii stuff ......

//start reading binary data
int m;
infile.read(reinterpret_cast < char * > (&m), sizeof(m));

Can I do the above (ie. read with getline() and then read binary? Also, that will read 1 byte (8 bits) into an int (is there an easier way?). How would I read 12 bits at a time (for a 12-bit color image)?

Thanks!

David

In other words, part of the file is ASCII and the rest is binary data.

>Can I do the above (ie. read with getline() and then read binary?
Sure, but you may encounter problems with newline conversion.

>How would I read 12 bits at a time (for a 12-bit color image)?
Use an array of 12 char:

char buf[12];

infile.read ( buf, sizeof buf );

but that is 12 bytes right? I need 12 bits.

And should I open the file as ios::binary or not?

Thanks,

Dave

You should open the file as ios::binary. There is really no way to directly read in bits. You have to read in the bytes and then write a function to read the bits from a byte.

So I just have to use the next integer number of bytes? I'm not too sure about how big data types are, but say a double is 2 bytes.

double d;
infile.read(reinterpret_cast < char * > (&d), sizeof(d));

This will read 16 bits... so now I have read too many bits. Then I have to manually split the byte and store the first half with the current byte and save the last half to put with the next byte? That sounds really painful...

Maybe I am thinking about this wrong?

Thanks,
Dave

One thing you could try is read in a set of bytes.

Copy 2 bytes (16 bits) over at a time to a temporary variable and then use the Bitwise AND operator to reset the bits you don't need.

The data type you are looking for is probably a short (2 bytes).

>but that is 12 bytes right? I need 12 bits.
Sorry, I misread your question. The smallest block of addressable memory you can use is a byte. If you need a bit count that isn't an even multiple of the byte size, you can either read "too much" and carry over the excess to the next operation using bitwise operators, or change your design to better fit the system.

>And should I open the file as ios::binary or not?
Yes, you should. That way you guarantee that textual conversions are not performed when you read the binary part. I imagine it's more important for the binary data be read correctly than the ASCII data. And you can always do manual newline conversions in the ASCII data if you need to.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.