Trying to use/include/compile 3rd party library, libmagic. C/C++ filetype detection

后端 未结 3 925
长发绾君心
长发绾君心 2021-01-21 10:18

After looking for a way to detect the filetype of a file stream, I found that the Unix file command uses libmagic and I\'m trying to make use of the library myself, but I can\'t

相关标签:
3条回答
  • 2021-01-21 10:53

    __FILE__ is a reserved pre-processing symbol macro used for debugging/logging purposes. Consider this as an example:

    // This file is called test.c
    char *p = NULL;
    if (!(p = malloc((1 * sizeof(char) + 1)))){
       printf("Error in file: %s @ line %d\n\tMalloc failed\n", __FILE__, __LINE__);
       exit(-1);
    }
    

    If the call to malloc failed you will see the output in the above example like this:

    Error in file: test.c @ line 23
           Malloc failed
    

    Notice how the code picks up the original source code. The above example illustrates the usage of this.

    I think your code should be something like this:

    // fileTypeTest.cpp, placed in file-5.03/src/ (source from link above)
    #include <stdio.h>
    #include "magic.h"
    int main(int argc, char **argv) {
      if (argc > 1){
         magic_t myt = magic_open(MAGIC_CONTINUE|MAGIC_ERROR/*|MAGIC_DEBUG*/|MAGIC_MIME);
         magic_load(myt,NULL);
         printf("magic output: '%s'\n",magic_file(myt,argv[1]));
         magic_close(myt);
      }
      return 0;
    }
    

    The code above checks if there is a parameter that is passed into this program and the parameter would be a filename, i.e. argv[0] points to the executable name (the compiled binary), argv[1] points to the array of chars (a string) indicating the filename in question.

    To compile it:

    g++ -I/usr/include -L/usr/lib/libmagic.so  fileTestType.cpp -o fileTestType
    g++ -L/usr/lib -lmagic fileTestType.cpp -o fileTestType
    

    Edit: Thanks Alok for pointing out the error here...

    If you are not sure where the libmagic reside, look for it in the /usr/local/lib, and /usr/local/include - this depends on your installation.

    See this to find the predefined macros here.

    Hope this helps, Best regards, Tom.

    0 讨论(0)
  • 2021-01-21 11:00

    Where is magic.h in the filesystem? Is the preprocessor finding it? If not, use -I<path>.

    0 讨论(0)
  • 2021-01-21 11:03

    I don't know why you think the above "obviously" doesn't work. See How to mix C and C++ in the C++ FAQ for details.

    Looks like magic.h has proper extern "C" { } enclosures. So, compiling your code with g++ should work nicely. You can #include <magic.h> in your .cpp file, and use all the libmagic functions.

    • Is there a particular error you're getting?
    • I have not checked your use of the libmagic functions.
    • You need to link with libmagic. Your g++ command needs -lmagic.
    • Since magic.h is most likely in a standard place, you should use #include <magic.h>.

    Tell us what your error is for more specific help.

    0 讨论(0)
提交回复
热议问题