views:

1509

answers:

5

I want to get the MIME type from a filename using C. Is there a way to do this without using a textfile containing MIME types and file extensions (i.e. Apache's file mime.types)?

Maybe there is a function to get the MIME type using the filename? I rather not use the file extension if I don't have to.

+3  A: 

If there was a way to do it, Apache wouldn't need its mime.types file!

The table has to be somewhere. It's either in a separate file which is parsed by your code, or it's hard coded into your software. The former is clearer the better solution...

It's also possible to guess at the MIME type of a file by examining the content of the file, i.e. header fields, data structures, etc. This is the approach used by the file(1) program and also by Apache's mod_mime_magic. In both cases they still use a separate text file to store the lookup rules rather than have any details hard-coded in the program itself.

Alnitak
Too bad. But aren't Apache able to find out mimetype without checking file extension? I know some of my friends who types i.e. http://domain.tld/picture and their Apache's returning a JPG. Is that because the mimetype is in the JPG?Thanks for a quick answer!
petsson
the Unix utility "file" makes (very) good guesses at file types by examining headers, data structures, etc. But it uses a separate file (typically /usr/share/file/magic) to store the lookup heuristics! Apache's mod_mime_magic works the same way.
Alnitak
Alright, then I know. Thanks again!
petsson
A: 

Also see this: how-to-add-file-extensions-based-on-file-type-on-linux-unix

csl
+2  A: 

as far as I know, the unix command file outputs the mime string with the option -i:

> file -i main.c
main.c: text/x-c charset=us-ascii
lImbus
How could that be used using C ?
Filip Ekberg
either by just calling it `system("file -i" pszFilename)` or looking in the code of `file`, rebuild the needed parts to parse `/usr/share/file/magic`
lImbus
Nice, I'll try this as soon as I can reach my UNIX server again. :)
petsson
A: 

You can download the source code of the "file" tool from here:

ftp://ftp.astron.com/pub/file/

The thing is it doesn't use a GPL like license, or any for that matter.

Ubersoldat
A: 

If you want to use a webservice, I just created this as part of my mimetype <-> icon service

http://stdicon.com/

For example :

http://stdicon.com/ext/html

It runs on appengine so it should have high availability.

Paul Tarjan