Reputation: 306
I'm writing a program in C, and I need to known the mime-type of a file.
I have yet searched with Google, and I found that I must include the 'file' UNIX utility in my project.
The source code of file
need configure
and make
. How I can include this in my project? Do I have to crop a part of the source code into a new file.c
and file.h
?
Upvotes: 0
Views: 1069
Reputation: 306
Thanks for yours answers and comments.
I solved with this:
const char *w_get_mime(const char *arg, const char *file, int line_no)
{
const char *magic_full;
magic_t magic_cookie;
if(arg == NULL)
w_report_error("called with NULL argument.",file,line_no,__func__,0,1,error);
else if ((magic_cookie = magic_open(MAGIC_MIME) ) == NULL)
report_error("unable to initialize magic library.",0,1,error);
else if (magic_load(magic_cookie, NULL) != 0)
{
magic_close(magic_cookie);
snprintf(globals.err_buff,MAX_BUFF,"cannot load magic database - %s .",magic_error(magic_cookie));
report_error(globals.err_buff,0,1,error);
}
magic_full = magic_file(magic_cookie, arg);
magic_close(magic_cookie);
return magic_full;
}
thanks a lot! :)
Upvotes: 0
Reputation: 28762
Do you want to guess the MIME type based on the extension, or do something like file
and examine the headers?
To get functionality similar to file
, you don't need to include file
in your project. Instead, you'll want to use libmagic which file
is based on. Unfortunately I'm not aware of a good source of documentation for this, but it's pretty straightforward.
magic_t magic = magic_open(MAGIC_MIME_TYPE);
magic_load(magic, NULL);
char *mime_type = magic_file(magic, "/path/to/file");
magic_close(magic);
Upvotes: 7