Q:

How to get the file format in C++/Qt

I need to write a program that allows me to read the names of every file in a directory, and also the type of a file. While I can get the filenames, I am unable to get how I am supposed to find the type. The only thing I can think of is to use its metadata, but I'm not even sure how to begin with that. 
I'm trying for an OS independent solution, but I'll be happy if it works only on Windows or Linux only as well.
Note: Please do NOT give solutions that involve searching for a dot, and anything in between. These days, almost no file had a .pdf or something attached to it. When you read the filename, all you get is sample, and not sample.txt.
Also, if it is not compatible with Qt, I'd appreciate if you could mention this in your answer so I can look take appropriate actions (I'm working on Qt because of GUI). 

A:

File Extension
As @CMLDMR pointed out, QFileInfo::suffix() and QFileInfo::completeSuffix() methods will return the file extension. However, file extension may be omitted, invalid, unknown, etc.
So, according to your actual question, you want to know the file format, not its extension as stated in the first revision.
File Format
Qt 5 has a class QMimeDatabase. It allows you to discover the file MIME type by its contents. Let's say we have an mpeg music file with no extension:
QMimeDatabase db;
QMimeType mime = db.mimeTypeForFile("C:/music", QMimeDatabase::MatchContent);
qDebug() << mime.name();            // Name of the MIME type ("audio/mpeg").
qDebug() << mime.suffixes();        // Known suffixes for this MIME type ("mp3", "mpga").
qDebug() << mime.preferredSuffix(); // Preferred suffix for this MIME type ("mp3").

File Extension + File Format
If you still want to give priority to the file extension and parse the file contents only if the suffix is not present, omit the QMimeDatabase::MatchContent argument – the default QMimeDatabase::MatchDefault will be used. See QMimeDatabase::MatchMode for more informtaion.

Note that Qt uses different MIME databases for different operating systems, so the results may vary.

A:

QFileInfo fi("/tmp/archive.tar.gz");
QString ext = fi.suffix();  // ext = "gz"

suffix function is give you a file extension.
OR
QFileInfo fi("/tmp/archive.tar.gz");
QString ext = fi.completeSuffix();  // ext = "tar.gz"

you can use each of other which one is correct for you.
This code independent but Qt. 
For Details LINK

