Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
scroll top