Libmagic is the library that commonly supports the file command on Unix system, other than Max OSX which has its own implementation. The library handles the loading of database files that describe the magic numbers used to identify various file types, as well as the associated mime types. The library also handles character set detections.
Installation
Ubuntu
$ sudo apt-get install libmagic-dev
Fedora
$ sudo yum install file-devel
openSUSE
$ sudo zypper install file-devel
Example
test.c
#include <stdio.h> #include <magic.h> int main(void) { char *actual_file = "/home/test/Downloads/image.jpg"; 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; }
Build the code
$ gcc -g test.c -lmagic
Out put
test@suse:~>$ ./a.out Loading default magic database image/jpeg; charset=binary
ref:
• What is libmagic in Linux?
• libmagic linux command man page
• libmagic.h example
#ubuntu #fedora #opensuse