How to check if a file is gzip compressed?

Deepak Prakash picture Deepak Prakash · May 19, 2011 · Viewed 23.9k times · Source

I have a C / C++ program which needs to read in a file that may or may not be gzip compressed. I know we can use gzread() from zlib to read in both compressed and uncompressed files - however, I want to use the zlib functions ONLY if the file is gzip compressed (for performance reasons).

So is there any way to programatically detect or check if a certain file is gzipped from C / C++?

Answer

Bruno Rohée picture Bruno Rohée · May 19, 2011

There is a magic number at the beginning of the file. Just read the first two bytes and check if they are equal to 0x1f8b.