libmagic/magic.h library tutorial with example. (It’s magic!)

Libmagic is generally used to determine a file type, for example if it’s a jpg, avi, or whatever, you can point it to a file and it will determine what sort of file it is using magic numbers.

I found only a few links on the library and the majority were all clones of the man file with this one being the best I found.

http://swoolley.org/man.cgi/3/libmagic

My googling skills/patience failed me it seems as I couldn’t find anything more detailed. However, I looked at some other projects that used it and experimented and got it working. Here is some example code, which takes “/file/you/want.yay” and returns a mime to it (e.g. text/x-c; charset=us-ascii). You can get it to return different stuff, check the previous link for more details.

#include <stdio.h>
#include <magic.h>

int main(void)
{
	char *actual_file = "/file/you/want.yay";
	const char *magic_full;
	magic_t magic_cookie;
	/*MAGIC_MIME tells magic to return a mime of the file, but you can specify different things*/
	magic_cookie = magic_open(MAGIC_MIME);
		if (magic_cookie == NULL) {
	        printf("unable to initialize magic library\n");
	        return 1;
		    }
	    printf("Loading default magic database\n");
	    if (magic_load(magic_cookie, NULL) != 0) {
	        printf("cannot load magic database - %s\n", magic_error(magic_cookie));
	        magic_close(magic_cookie);
	        return 1;
	    }
	magic_full = magic_file(magic_cookie, actual_file);
	printf("%s\n", magic_full);
	magic_close(magic_cookie);
        return 0;
}

To compile it do: “gcc magic_test.c -o magics -lmagic”. Furthermore make sure the libmagic library is installed. “apt-get install libmagic-dev” should do it if you’re using a machine with debian/ubuntu.

Apologies for the bad formatting, it seems eclipse and wordpress don’t agree with each other.


Leave a Reply

Your email address will not be published. Required fields are marked *