Libmagicxx v10.0.3
A modern C++23 wrapper for libmagic — the library that powers the Unix file command.
Loading...
Searching...
No Matches
Recognition::Magic Class Reference

A modern C++23 wrapper for libmagic — the library that powers the Unix file command. More...

#include <magic.hpp>

Classes

class  MagicPrivate
 PIMPL implementation class for Magic. More...

Public Types

enum  Flags : unsigned long long {
  None = 0ULL , Debug = 1ULL << 0 , Symlink = 1ULL << 1 , Compress = 1ULL << 2 ,
  Devices = 1ULL << 3 , MimeType = 1ULL << 4 , ContinueSearch = 1ULL << 5 , CheckDatabase = 1ULL << 6 ,
  PreserveAtime = 1ULL << 7 , Raw = 1ULL << 8 , Error = 1ULL << 9 , MimeEncoding = 1ULL << 10 ,
  Mime = 1ULL << 11 , Apple = 1ULL << 12 , Extension = 1ULL << 13 , CompressTransp = 1ULL << 14 ,
  NoCompressFork = 1ULL << 15 , Nodesc = 1ULL << 16 , NoCheckCompress = 1ULL << 17 , NoCheckTar = 1ULL << 18 ,
  NoCheckSoft = 1ULL << 19 , NoCheckApptype = 1ULL << 20 , NoCheckElf = 1ULL << 21 , NoCheckText = 1ULL << 22 ,
  NoCheckCdf = 1ULL << 23 , NoCheckCsv = 1ULL << 24 , NoCheckTokens = 1ULL << 25 , NoCheckEncoding = 1ULL << 26 ,
  NoCheckJson = 1ULL << 27 , NoCheckSimh = 1ULL << 28 , NoCheckBuiltin = 1ULL << 29
}
 Flags for configuring Magic behavior. More...
enum class  Parameters : std::size_t {
  Parameters::IndirMax = 0uz , Parameters::NameMax = 1uz , Parameters::ElfPhnumMax = 2uz , Parameters::ElfShnumMax = 3uz ,
  Parameters::ElfNotesMax = 4uz , Parameters::RegexMax = 5uz , Parameters::BytesMax = 6uz , Parameters::EncodingMax = 7uz ,
  Parameters::ElfShsizeMax = 8uz , Parameters::MagWarnMax = 9uz
}
 Parameters for tuning Magic behavior limits. More...
using FlagsMaskT = std::bitset<30uz>
 Bitmask type representing a set of Magic::Flags used to configure the Magic instance.
using FileTypeT = std::string
 String type representing the detected type of a file.
using ErrorMessageT = std::string
 String type representing an error message from file identification.
using ExpectedFileTypeT = std::expected<FileTypeT, ErrorMessageT>
 Result type for file identification, containing either a file type or an error message.
using FileTypeMapT = std::map<std::filesystem::path, FileTypeT>
 Map from file paths to their detected types.
using FileTypeEntryT = FileTypeMapT::value_type
 Key-value pair representing a single file and its detected type.
using ExpectedFileTypeMapT
 Map from file paths to expected file type results (success or error).
using ExpectedFileTypeEntryT = ExpectedFileTypeMapT::value_type
 Key-value pair representing a single file and its expected file type result.
using ProgressTrackerT = Utility::SharedProgressTrackerT
 Alias for a shared pointer to a progress tracker used for monitoring file identification progress.
using FlagsContainerT = std::vector<Flags>
 Container type holding a collection of Magic::Flags.
using ParameterValueMapT = std::map<Parameters, std::size_t>
 Map from Magic::Parameters to their corresponding values.
using ParameterValueT = ParameterValueMapT::value_type
 Key-value pair representing a single parameter and its value.

Public Member Functions

 Magic () noexcept
 Default constructor. Creates an unopened Magic instance.
 Magic (FlagsMaskT flags_mask, const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE)
 Construct and initialize Magic with flags and database.
 Magic (FlagsMaskT flags_mask, const std::nothrow_t &tag, const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE) noexcept
 Construct and initialize Magic with flags and database (noexcept version).
 Magic (const FlagsContainerT &flags_container, const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE)
 Construct and initialize Magic with a container of flags.
 Magic (const FlagsContainerT &flags_container, const std::nothrow_t &tag, const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE) noexcept
 Construct and initialize Magic with a container of flags (noexcept version).
 Magic (Magic &&other) noexcept
 Move constructor.
 Magic (const Magic &)=delete
 Deleted copy constructor.
Magicoperator= (Magic &&other) noexcept
 Move assignment operator.
Magicoperator= (const Magic &)=delete
 Deleted copy assignment operator.
 ~Magic ()
 Destructor.
 operator bool () const noexcept
 Boolean conversion operator for validity checking.
void Close () noexcept
 Close the Magic instance.
FlagsContainerT GetFlags () const
 Get the current flags.
std::optional< FlagsContainerTGetFlags (const std::nothrow_t &tag) const noexcept
 Get the current flags (noexcept version).
std::size_t GetParameter (Parameters parameter) const
 Get the value of a specific parameter.
std::optional< std::size_t > GetParameter (Parameters parameter, const std::nothrow_t &tag) const noexcept
 Get the value of a specific parameter (noexcept version).
ParameterValueMapT GetParameters () const
 Get all parameter values.
std::optional< ParameterValueMapTGetParameters (const std::nothrow_t &tag) const noexcept
 Get all parameter values (noexcept version).
FileTypeT IdentifyFile (const std::filesystem::path &path) const
 Identify the type of a single file.
ExpectedFileTypeT IdentifyFile (const std::filesystem::path &path, const std::nothrow_t &tag) const noexcept
 Identify the type of a single file (noexcept version).
FileTypeMapT IdentifyFiles (const std::filesystem::path &directory, std::filesystem::directory_options option=std::filesystem::directory_options::follow_directory_symlink) const
 Identify all files in a directory.
FileTypeMapT IdentifyFiles (const std::filesystem::path &directory, ProgressTrackerT progress_tracker, std::filesystem::directory_options option=std::filesystem::directory_options::follow_directory_symlink) const
 Identify all files in a directory with progress tracking.
ExpectedFileTypeMapT IdentifyFiles (const std::filesystem::path &directory, const std::nothrow_t &tag, std::filesystem::directory_options option=std::filesystem::directory_options::follow_directory_symlink) const noexcept
 Identify all files in a directory (noexcept version).
ExpectedFileTypeMapT IdentifyFiles (const std::filesystem::path &directory, const std::nothrow_t &tag, ProgressTrackerT progress_tracker, std::filesystem::directory_options option=std::filesystem::directory_options::follow_directory_symlink) const noexcept
 Identify all files in a directory with progress tracking (noexcept version).
FileTypeMapT IdentifyFiles (const Utility::FileContainer auto &files) const
 Identify multiple files from a container.
FileTypeMapT IdentifyFiles (const Utility::FileContainer auto &files, ProgressTrackerT progress_tracker) const
 Identify multiple files with progress tracking.
ExpectedFileTypeMapT IdentifyFiles (const Utility::FileContainer auto &files, const std::nothrow_t &tag) const noexcept
 Identify multiple files from a container (noexcept version).
ExpectedFileTypeMapT IdentifyFiles (const Utility::FileContainer auto &files, const std::nothrow_t &tag, ProgressTrackerT progress_tracker) const noexcept
 Identify multiple files with progress tracking (noexcept version).
bool IsDatabaseLoaded () const noexcept
 Check if a magic database is loaded.
bool IsOpen () const noexcept
 Check if the Magic instance is open.
bool IsValid () const noexcept
 Check if the Magic instance is valid for file identification.
void LoadDatabaseFile (const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE)
 Load a magic database file.
bool LoadDatabaseFile (const std::nothrow_t &tag, const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE) noexcept
 Load a magic database file (noexcept version).
void Open (FlagsMaskT flags_mask)
 Open Magic with specified flags.
bool Open (FlagsMaskT flags_mask, const std::nothrow_t &tag) noexcept
 Open Magic with specified flags (noexcept version).
void Open (const FlagsContainerT &flags_container)
 Open Magic with a container of flags.
bool Open (const FlagsContainerT &flags_container, const std::nothrow_t &tag) noexcept
 Open Magic with a container of flags (noexcept version).
void SetFlags (FlagsMaskT flags_mask)
 Set new flags for the Magic instance.
bool SetFlags (FlagsMaskT flags_mask, const std::nothrow_t &tag) noexcept
 Set new flags (noexcept version).
void SetFlags (const FlagsContainerT &flags_container)
 Set new flags from a container.
bool SetFlags (const FlagsContainerT &flags_container, const std::nothrow_t &tag) noexcept
 Set new flags from a container (noexcept version).
void SetParameter (Parameters parameter, std::size_t value)
 Set a single parameter value.
bool SetParameter (Parameters parameter, std::size_t value, const std::nothrow_t &tag) noexcept
 Set a single parameter value (noexcept version).
void SetParameters (const ParameterValueMapT &parameters)
 Set multiple parameter values.
bool SetParameters (const ParameterValueMapT &parameters, const std::nothrow_t &tag) noexcept
 Set multiple parameter values (noexcept version).

Static Public Member Functions

static bool Check (const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE) noexcept
 Check magic database file for validity.
static bool Compile (const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE) noexcept
 Compile a magic database file.
static std::string GetVersion () noexcept
 Get the libmagic library version.

Static Public Attributes

static std::string_view DEFAULT_DATABASE_FILE {MAGIC_DEFAULT_DATABASE_FILE}
 Path to the default magic database file.

Private Types

using DefaultFileContainerT = std::vector<std::filesystem::path>
 Default container type for file paths used in implementation.

Private Member Functions

FileTypeMapT IdentifyDirectoryImpl (const std::filesystem::path &directory, std::filesystem::directory_options option, ProgressTrackerT progress_tracker=Utility::MakeSharedProgressTracker()) const
 Implementation for directory identification (throwing version).
ExpectedFileTypeMapT IdentifyDirectoryImpl (const std::filesystem::path &directory, const std::nothrow_t &tag, std::filesystem::directory_options option, ProgressTrackerT progress_tracker=Utility::MakeSharedProgressTracker()) const noexcept
 Implementation for directory identification (noexcept version).
FileTypeMapT IdentifyContainerImpl (const DefaultFileContainerT &files, ProgressTrackerT progress_tracker=Utility::MakeSharedProgressTracker()) const
 Implementation for container identification (throwing version).
ExpectedFileTypeMapT IdentifyContainerImpl (const DefaultFileContainerT &files, const std::nothrow_t &tag, ProgressTrackerT progress_tracker=Utility::MakeSharedProgressTracker()) const noexcept
 Implementation for container identification (noexcept version).

Private Attributes

std::unique_ptr< MagicPrivatem_impl
 Pointer to the implementation (Pimpl idiom).

Friends

std::string ToString (Magic::Flags flag)
 Friend declaration for ToString(Flags) free function.
std::string ToString (Magic::Parameters parameter)
 Friend declaration for ToString(Parameters) free function.

Detailed Description

A modern C++23 wrapper for libmagic — the library that powers the Unix file command.

The Magic class provides a high-level, type-safe interface for identifying file types based on their content (magic numbers) rather than file extensions. It wraps the underlying libmagic C library with RAII semantics, exception safety, and modern C++ features.

Key Features

  • RAII Resource Management: Automatic cleanup of libmagic resources
  • Dual API: Throwing and noexcept overloads for all operations
  • Progress Tracking: Monitor batch file identification progress
  • Flexible Configuration: Extensive flags and parameters for customization
  • Thread Safety: Each Magic instance is independent (not thread-safe within instance)

Lifecycle

A Magic instance follows a three-state lifecycle:

* +-----------------------------------------------------------------------------------+
* |                              Magic State Diagram                                  |
* +-----------------------------------------------------------------------------------+
* |                                                                                   |
* |  Constructor()                                       Constructor(flags)           |
* |       |                                                     |                     |
* |       V                                                     V                     |
* |   +------------+  Open(flags)  +------------+         +------------+              |
* |   |   CLOSED   |-------------->|   OPENED   |<--------|   VALID    |              |
* |   +--+---------+               +--+------+--+  Open   +---------+--+              |
* |      |    ^   ^                   |  ^   |     (flags)    ^     |                 |
* |      +----+   |                   |  +---+                |     |                 |
* |      Close()  |                   |  Open(flags)          |     |                 |
* |               |                   |                       |     |                 |
* |               |                   +-----------------------+     |                 |
* |               |                       LoadDatabaseFile()        |                 |
* |               |                                                 |                 |
* |               +-------------------------------------------------+                 |
* |                                     Close()                                       |
* |                                                                                   |
* +-----------------------------------------------------------------------------------+
* 

State Descriptions

State IsOpen() IsDatabaseLoaded() IsValid() Can Identify?
Closed false false false No
Opened true false false No
Valid true true true Yes

Usage Patterns

// Pattern 1: Single-step construction (recommended)
Magic magic1{Magic::Flags::Mime}; // Opens and loads default database
assert(magic1.IsValid());
// Pattern 2: Manual lifecycle control
Magic magic2; // Closed state
assert(!magic2.IsOpen());
magic2.Open(Magic::Flags::Mime); // Opened state
assert(magic2.IsOpen() && !magic2.IsDatabaseLoaded());
magic2.LoadDatabaseFile(); // Valid state
assert(magic2.IsValid());
// Pattern 3: Reopen with different flags
magic2.Open(Magic::Flags::Extension); // Back to Opened (database unloaded)
magic2.LoadDatabaseFile(); // Valid again with new flags
// Pattern 4: Check before use
if (magic2.IsValid()) {
auto type = magic2.IdentifyFile("file.txt");
}
// Pattern 5: Boolean conversion (same as IsValid)
if (magic2) {
auto type = magic2.IdentifyFile("file.txt");
}
A modern C++23 wrapper for libmagic — the library that powers the Unix file command.
Definition magic.hpp:216
Magic() noexcept
Default constructor. Creates an unopened Magic instance.
Definition magic.cpp:2421
void LoadDatabaseFile(const std::filesystem::path &database_file=DEFAULT_DATABASE_FILE)
Load a magic database file.
Definition magic.cpp:2638
FileTypeT IdentifyFile(const std::filesystem::path &path) const
Identify the type of a single file.
Definition magic.cpp:2530
@ Mime
Definition magic.hpp:328
@ Extension
Definition magic.hpp:330
void Open(FlagsMaskT flags_mask)
Open Magic with specified flags.
Definition magic.cpp:2651
bool IsValid() const noexcept
Check if the Magic instance is valid for file identification.
Definition magic.cpp:2633
bool IsOpen() const noexcept
Check if the Magic instance is open.
Definition magic.cpp:2628
bool IsDatabaseLoaded() const noexcept
Check if a magic database is loaded.
Definition magic.cpp:2623
Note
Close() is idempotent—safe to call multiple times on any state.
The destructor automatically closes the instance.

Output Formats

The Magic class can return file type information in several formats, controlled by the Flags enum:

Flag Output Example
None "ASCII text"
MimeType "text/plain"
MimeEncoding "us-ascii"
Mime "text/plain; charset=us-ascii"
Extension "txt/asc"
Apple "TEXT/ttxt"
Note
Each Magic instance holds its own libmagic cookie. Instances are move-only (not copyable) due to resource ownership.
Warning
The Magic class is not thread-safe. Do not share a single instance across threads. Create separate instances per thread.
See also
Magic::Flags for configuration options
Magic::Parameters for tunable limits
MagicException for error handling
Since
10.0.0
Examples
magic_examples.cpp.

Member Typedef Documentation

◆ DefaultFileContainerT

using Recognition::Magic::DefaultFileContainerT = std::vector<std::filesystem::path>
private

Default container type for file paths used in implementation.

◆ ErrorMessageT

using Recognition::Magic::ErrorMessageT = std::string

String type representing an error message from file identification.

◆ ExpectedFileTypeEntryT

using Recognition::Magic::ExpectedFileTypeEntryT = ExpectedFileTypeMapT::value_type

Key-value pair representing a single file and its expected file type result.

◆ ExpectedFileTypeMapT

Initial value:
std::map<
std::filesystem::path,
>
std::expected< FileTypeT, ErrorMessageT > ExpectedFileTypeT
Result type for file identification, containing either a file type or an error message.
Definition magic.hpp:244

Map from file paths to expected file type results (success or error).

◆ ExpectedFileTypeT

Result type for file identification, containing either a file type or an error message.

◆ FileTypeEntryT

using Recognition::Magic::FileTypeEntryT = FileTypeMapT::value_type

Key-value pair representing a single file and its detected type.

◆ FileTypeMapT

using Recognition::Magic::FileTypeMapT = std::map<std::filesystem::path, FileTypeT>

Map from file paths to their detected types.

◆ FileTypeT

using Recognition::Magic::FileTypeT = std::string

String type representing the detected type of a file.

◆ FlagsContainerT

Container type holding a collection of Magic::Flags.

◆ FlagsMaskT

using Recognition::Magic::FlagsMaskT = std::bitset<30uz>

Bitmask type representing a set of Magic::Flags used to configure the Magic instance.

◆ ParameterValueMapT

using Recognition::Magic::ParameterValueMapT = std::map<Parameters, std::size_t>

Map from Magic::Parameters to their corresponding values.

◆ ParameterValueT

using Recognition::Magic::ParameterValueT = ParameterValueMapT::value_type

Key-value pair representing a single parameter and its value.

◆ ProgressTrackerT

Alias for a shared pointer to a progress tracker used for monitoring file identification progress.

See also
Utility::ProgressTracker

Member Function Documentation

◆ IdentifyContainerImpl() [1/2]

Magic::ExpectedFileTypeMapT Recognition::Magic::IdentifyContainerImpl ( const DefaultFileContainerT & files,
const std::nothrow_t & tag,
ProgressTrackerT progress_tracker = Utility::MakeSharedProgressTracker() ) const
nodiscardprivatenoexcept

Implementation for container identification (noexcept version).

◆ IdentifyContainerImpl() [2/2]

Magic::FileTypeMapT Recognition::Magic::IdentifyContainerImpl ( const DefaultFileContainerT & files,
ProgressTrackerT progress_tracker = Utility::MakeSharedProgressTracker() ) const
nodiscardprivate

Implementation for container identification (throwing version).

◆ IdentifyDirectoryImpl() [1/2]

Magic::ExpectedFileTypeMapT Recognition::Magic::IdentifyDirectoryImpl ( const std::filesystem::path & directory,
const std::nothrow_t & tag,
std::filesystem::directory_options option,
ProgressTrackerT progress_tracker = Utility::MakeSharedProgressTracker() ) const
nodiscardprivatenoexcept

Implementation for directory identification (noexcept version).

◆ IdentifyDirectoryImpl() [2/2]

Magic::FileTypeMapT Recognition::Magic::IdentifyDirectoryImpl ( const std::filesystem::path & directory,
std::filesystem::directory_options option,
ProgressTrackerT progress_tracker = Utility::MakeSharedProgressTracker() ) const
nodiscardprivate

Implementation for directory identification (throwing version).

◆ ToString [1/2]

std::string ToString ( Magic::Flags flag)
friend

Friend declaration for ToString(Flags) free function.

Returns the symbolic name of a single flag value.

Parameters
[in]flagThe flag to convert.
Returns
String name of the flag (e.g., "Mime", "MimeType").
std::println("{}", ToString(Magic::Flags::Mime));
// Output: Mime
friend std::string ToString(Flags)
Friend declaration for ToString(Flags) free function.
Definition magic.cpp:2355
See also
Magic::Flags
Since
10.0.0

◆ ToString [2/2]

std::string ToString ( Magic::Parameters parameter)
friend

Friend declaration for ToString(Parameters) free function.

Returns the symbolic name of a single parameter value.

Parameters
[in]parameterThe parameter to convert.
Returns
String name of the parameter (e.g., "BytesMax", "RegexMax").
// Output: BytesMax
@ BytesMax
Definition magic.hpp:389
See also
Magic::Parameters
Since
10.0.0

Member Data Documentation

◆ DEFAULT_DATABASE_FILE

std::string_view Recognition::Magic::DEFAULT_DATABASE_FILE {MAGIC_DEFAULT_DATABASE_FILE}
static

Path to the default magic database file.

This static member holds the path to the default magic database file that was configured at build time. It is used as the default parameter for LoadDatabaseFile() and constructors.

Note
On Linux, this typically points to "/usr/share/magicxx/databases/magic". On Windows, this typically points to "C:/Program Files/magicxx/databases/magic".
See also
LoadDatabaseFile()
Since
10.0.0
Examples
magic_examples.cpp.

◆ m_impl

std::unique_ptr<MagicPrivate> Recognition::Magic::m_impl
private

Pointer to the implementation (Pimpl idiom).


The documentation for this class was generated from the following files: