Reading a binary file

Started by
1 comment, last by Ryder052 8 years, 10 months ago

I have created a binary file. The very beginning of it are three unsigned shorts. As a confirmation I attach Byte Reader screenshot.

The numbers are 250, 188 and 10. All checks out, doesn't it?

Now I'm trying to read it.


ifstream frame;
frame.open(filename, ios::binary);

USHORT* whd;
char* whdBuffer = new char(sizeof(USHORT)*3);

frame.read(whdBuffer, sizeof(USHORT)*3);
whd = (USHORT*)whdBuffer;

printf("%d %d %d\n", whd[0], whd[1], whd[2]);
delete[] whdBuffer;

The output is:

64774 65021 44029

What's wrong?

Advertisement

char* whdBuffer = new char(sizeof(USHORT)*3);

What's this? I think it allocates a single char and puts the initial value 2 * 3 = 6 inside it, which is likely not what you want. Did you mean:


char* whdBuffer = new char[sizeof(USHORT)*3];

At this point you are probably corrupting the stack by asking ifstream to write 6 bytes into an array that contains only space for one byte, so fix that and try again.

Secondly, reinterpreting a char pointer as a USHORT (unsigned short) pointer is in general illegal and undefined behaviour because USHORT has stricter alignment requirements than char (doing the opposite is valid, though). If you need an array of USHORT, ask for an array of USHORT. It will work fine in this case because the "new" operator is guaranteed to return "sufficiently aligned" memory for all primitive types, but this may not hold in general (especially if you reinterpret a pointer into the middle of an array) and is a bad habit to get into, so just avoid reinterpreting pointers like that. Many C++ programmers are actually not aware of alignment constraints because the x86 processor in your desktop fixes up the unaligned accesses in hardware at (some) performance cost, however code that just freely reinterprets pointers like there's no tomorrow is liable to fail hard on less friendly processors like some ARM (mobile) processors wink.png

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

Thanks. It wasn't the problem though. I just had the file in another directory. Error checking ftw... Solved. Final code:


ifstream frame;
frame.open(filename, ios::binary);


USHORT whd[3];
frame.read((char*)whd, sizeof(USHORT)*3);

This topic is closed to new replies.

Advertisement