I'm writing a program, part of which consists of determining if a given file is a PNG. Knowing that a file doesn't have to be named with its respective filename extension to be of a certain type, I decided to check for it's header. However, after not being able to think of anything better, I wrote this if statement with loads of &&...

uint8_t buffer[sizeof(uint8_t) * size];
int fileType;

if (fread(buffer, sizeof(uint8_t) * size, 1, fp) == 1) {

    if (buffer[0] == 137 && buffer[1] == 80  &&
            buffer[2] == 78  && buffer[3] == 71  &&
            buffer[4] == 13  && buffer[5] == 10  &&
            buffer[6] == 26  && buffer[7] == 10) 
                fileType = PNG;


size has been determined before and PNG is from an enum type, in case there's any confusion.

I tried having the header bits of the PNG file format as a macro, but it seemed much too complicated (because of the way they are read onto a buffer) to check if the given file's bits are the same as that macro. I also tried using strings, but it also seemed much more complicated than this.

I was wondering, how would you go about refactoring this? Or, since there probably is a better way, how else could I check if the PNG header is present in a given file?

closed as off-topic by Kilian Foth, Bart van Ingen Schenau, Doc Brown, Martin Maat, BobDalgleish Jan 22 at 22:35

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in explaining, writing or debugging code are off-topic here. These can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question (see Minimal, Complete, and Verifiable Example)." – Martin Maat, BobDalgleish
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    Why not just use libpng or similar to try to open it instead of reinventing the wheel? – whatsisname Jan 20 at 23:38
  • 3
    I'm voting to close this question as off-topic because it should go on codereview.stackexchange.com – Kilian Foth Jan 21 at 7:08
  • @whatsisname I guess this is what happens when someone doesn't know that the wheel exists. I'll give that a try. Thanks. – Areg Sarvazyan Jan 21 at 12:25

Use memcmp to compare the PNG header against the first bytes of the file. Other than that you can't avoid opening and reading the file.

Maybe you should fseek back to the start, to reset the file descriptor offset.

Not the answer you're looking for? Browse other questions tagged or ask your own question.