Reading a file as ascii and then binary?
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
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
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 );
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
but that is 12 bytes right? I need 12 bits.
And should I open the file as ios::binary or not?
Thanks,
Dave
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
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
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
>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.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401