0

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?

Community
  • 1
  • 1
tux_mind
  • 306
  • 1
  • 5
  • 15
  • "I need to know the mime-type of a file" -> Possible duplicate of http://stackoverflow.com/questions/9137732/how-to-generate-the-http-content-type-header-in-c/9137758, which I answered as http://stackoverflow.com/a/9137758/960195 – Adam Mihalcin Feb 05 '12 at 21:07
  • You need more than the binary. File uses /etc/magic, which contains "fingerprints" for the various file types. Best/simplest way is simply to use popen() or system(). – wildplasser Feb 05 '12 at 21:10
  • Using `popen` or `system` is (always) a very bad idea. There's `libmagic`, or if you want to invoke `file(1)`, you should use `posix_spawn`. – R.. GitHub STOP HELPING ICE Feb 05 '12 at 23:16

2 Answers2

7

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);
Michael Mior
  • 28,107
  • 9
  • 89
  • 113
  • 1
    Other example usage: http://stackoverflow.com/questions/2105816/trying-to-use-include-compile-3rd-party-library-libmagic-c-c-filetype-detect – Mat Feb 05 '12 at 21:15
0

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! :)

Toto
  • 89,455
  • 62
  • 89
  • 125
tux_mind
  • 306
  • 1
  • 5
  • 15