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
__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 fileTestTypeg++ -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.
Where is magic.h
in the filesystem? Is the preprocessor finding it? If not, use -I<path>
.
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.
g++
command needs -lmagic
.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.