ofFile Binary Mode

I’m trying to write a simple checksum function. It opens an image file under binary mode & reads blocks of data.

For some reason, it doesn’t seem to be reading in binary mode. I can’t get anything after the 5th position, even when getSize() reports its over 40000 in size.

This a bug? or have I just forgotten how to read files?

Block of code:

cout << "\n\n";

ofFile file;
file.open(path_to_some_png, ofFile::ReadOnly, true);

if (file.good()) {
	const int CHECKSUM_BLOCK_SIZE = 16;

	char *pc = new char[CHECKSUM_BLOCK_SIZE];
	do {

		memset(pc, NULL, CHECKSUM_BLOCK_SIZE); // make it all 00
		file.get(pc, CHECKSUM_BLOCK_SIZE);

		for (int i = 0; i < 16; i++) { // print
			cout << ((unsigned)pc[i] < 16 ? " 0" : " ") << hex << (unsigned)pc[i];
		}
		cout << "\n";

	} while (file.good());
	delete[] pc;
}

My code’s output:

ffffff89 50 4e 47 0d 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Ignoring the initial ffffff garbage above, you can see it stops after the return, 0D.

Real hex dump (32 chars) of the sample PNG:

89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52
00 00 02 00 00 00 02 00 08 06 00 00 00 F4 78 D4

try using read instead of get. get is meant to be used to read strings and it’ll stop after the first breakline: http://www.cplusplus.com/reference/istream/istream/get/

another possibility is to use ofBuffer to read the whole file to memory and then just iterate it in memory which will be faster even if it uses more memory but unless the file is too big it’s probably worth it:

ofFile file(path_to_some_png, ofFile::ReadOnly, true);
ofBuffer buffer(file);
for (int i = 0; i < CHECKSUM_BLOCK_SIZE; i++) {
    cout << (unsigned)buffer.getData()[i] << endl;
}

nice, so ofBuffer is a memory mapped file?
That did the trick! thanks

not really, it’s just a buffer in memory, when you create it using an istream it’ll read it completely in memory.