Qore magic Module  0.0.2
Qore Magic Module

This is a module for recognizing the type of data contained in a computer file using so called magic numbers. It is a wrapper around libmagic C library (covered by the standard Berkeley Software Distribution copyright).

This module is released under the LGPL 2.1 and is tagged as such in the module's header (meaning it can be loaded unconditionally regardless of how the Qore library was initialized).

This module provides the following class:

  • Magic

The *Single Unix Specification (SUS)* specifies that a series of tests are performed on the file specified on the command line:

  • if the file cannot be read, its status undetermined, or its type undetermined, Magic will indicate that the file was processed and its type was undetermined.
  • file must be able to determine the types directory, FIFO, socket, block special file, and character special file
  • zero-length files are identified as such
  • an initial part of file is considered and Magic is to use position-sensitive tests
  • the entire file is considered and Magic is to use context-sensitive tests
  • the file is identified as a data file

Magic position-sensitive tests are normally implemented by matching various locations within the file against a textual database of magic numbers. This differs from other simpler methods such as file extensions and schemes like MIME.

In most implementations, the file command uses a database to drive the probing of the lead bytes. That database is implemented in file called magic, whose location is usually in /etc/magic, /usr/share/file/magic or a similar location.

To use the module in a Qore script, use the %requires directive as in the following example:

%new-style
%strict-args
%require-types
%enable-all-warnings
# import the magic module API
%requires magic
Magic m(MAGIC_MIME_TYPE);
printf("%y\n", m.file("/etc/resolv.conf"));

The above command would result in the following output when executed on a standard UNIX or UNIX-like system:

"inode/symlink; charset=binary"