How can I find the underlying file type in C++?

c++, linux, windows

Solution

File utility uses libmagic library. It recognises filetype parsing "special" fields in the file. Of course, you can program by yourself recognition of some formats, but sometimes this requires plenty of work. E.g. when you try to differentiate between different formats of MP4.

Developers of that library did pretty huge amount of work. So it's adviced to use their results if you want to get god results in saying what type format you deal with.(this is a big sphere, really, and if knowing what type format you are working with,better rely on them then on your code)

File utility - http://www.darwinsys.com/file/ You can download source code and see how really many different recognition types they use. Download archive file-4.26 -> magic -> Magdir

Personally I had luck with compiling file 4.26 on Windows ftp://ftp.astron.com/pub/file/

Caution It's merely a convention that files of certain formats should have predefined signatures and it's true almost always and helps identify formats of files properly. If it's not point of concern, you can surely trust signature. But just keep in mind that anyone having enough knowledge and wish can open a file in hex editor and playing with bits make another format of file.

Problem

In *nix system there is a command called 'file', which can tell you the underlying type of a file. Say, if you rename a binary executable's name into foo.txt, or you rename a mp3 file into .txt, the system will always tell you the real type of the file. But in Windows, there seems no such functionality, if you rename an executable into .txt, you cannot execute it. Can anyone explain to me how this is done in *nix system, and how can I find the real type of a file using C++, especially in windows, where I cannot use std::system("file blah")?

Original source