I'm currently trying to read a bitmap file header using the following code:
#include <fstream>
using namespace std;
struct BitMapFileHeader {
uint16_t bfType;
uint32_t bfSize;
uint16_t bfReserved1;
uint16_t bfReserved2;
uint32_t bfOffBits;
} file_header;
int main() {
ifstream fin;
fin.open("input.bmp", ios::binary);
fin.read(reinterpret_cast<char*>(&file_header), sizeof(file_header));
}
The first few bytes of my file are 42 4D 36 53 07 00 00 00
. file_header.bfType
shows the correct value of 19778
contained in the 1st and 2nd bytes, however filder_header.bfSize
shows 7
, which is stored in the 5th byte and it seems to skip the 3rd and 4th bytes.
It appears that I have encountered an issue that was mentioned in the comment of the second answer of this question. Despite identifying the issue, I have no clue how to resolve it. Can someone point me in the right direction?
Edit: some do not recommend packing struct members due to performance issues with unaligned memory access. Apart from populating each struct member one by one, is there any way to avoid this performance penalty?