c++fileiobinarymagic-numbers

C++ read and compare magic number from file


i have i file i want to read in C++. First thing i have to read and check is the magic number of the file. In my case it is the Hex-Value: 0xABCDEF00

I read and compare the number this way:

ifstream input ("C:/Desktop/myfile", ios::binary);
if (input.is_open()) {
input.seekg(0, ios::beg);
unsigned char magic[4] = {0};
input.read((char*)magic, sizeof(magic));

if(magic[0] == 0xAB &&
   magic[1] == 0xCD &&
   magic[2] == 0xEF &&
   magic[3] == 0x00) {
   cout << "It's my File!" << endl;
} else {
   cout << "Unknown File!" << endl;
}
}

This works very well, but is there a way to compare the whole read char[]-Array at once? Like this way:

unsigned int magicNumber = 0xABCDEF00;
... same code for reading file as above ...
Instead of checking each Array-Entry a way like this: 

if(magic == magicNumber) {
    do something ...
}

Would be nice to know if there is such a way - if not thanks for teeling me that there is no such way :)


Solution

  • Good old memcmp could help here. Once you have read the unsigned char magic[4] you can do the comparison as simply as:

    const unsigned char magicref[4] = {0xAB, 0xCD, 0xEF, 0}
    if (memcmp(magic, magicref, sizeof(magic)) == 0) {
        // do something ...
    }
    

    This is endianness independant.

    If you know what you platform will give you for the magic number and do not care about portability on other platforms, you can directly process everything as uint32_t:

    uint32_t magic, refmagic = 0xABCDEF00;  // big endian here...
    input.read(reinterpret_cast<char *>(&magic), sizeof(magic)); // directly load bytes into uint32_t
    if (magic == refmagic) {
        //do something...
    }
    

    This is not portable across different platforms, but can be used in simple cases provided a comment in bold red flashing font saying BEWARE: use only on big endian system