Conoscere il mime-type di un file mediante le funzioni esterne del API di libmagic

Da Gambas-it.org - Wikipedia.

E' possibile conoscere il Mime-Type di un file mediante alcune risorse della libreria Libmagic.

Sarà necessario avere installata nel proprio sistema e richiamare in Gambas la libreria (nella sua attuale versione): libmagic.so.1.0.0

Mostriamo un semplice esempio:

Library "libmagic:1.0.0"

Private MAGIC_MIME_TYPE As Integer = &10
Private MAGIC_MIME_ENCODING As Integer = &400
Private MAGIC_MIME As Integer = MAGIC_MIME_TYPE Or MAGIC_MIME_ENCODING

' magic_t magic_open(int)
' Creates a magic cookie pointer and returns it.
Private Extern magic_open(mg As Integer) As Pointer

' int magic_load(magic_t, const char *)
' Loads the the colon separated list of database files passed in as file name.
Private Extern magic_load(magic_t As Pointer, filename As String) As Integer

' const char *magic_file(magic_t, const char *)
' Returns a textual description of the contents of the file.
Private Extern magic_file(magic_t As Pointer, filename As String) As String

' void magic_close(magic_t)
' Closes the magic database and deallocates any resources used.
Private Extern magic_close(magic_t As Pointer)
 

Public Sub Main()
 
 Dim magic As Pointer
 Dim err As Integer

 magic = magic_open(MAGIC_MIME)
 If magic == 0 Then Error.Raise("Impossibile inizializzare la libreria 'magic' !")
  
 err = magic_load(magic, Null)
 If err <> 0 Then
   ChiudeMagic(magic)
   Error.Raise("Impossibile caricare il database di 'magic' !")
 Endif
  
 Print magic_file(magic, "/percorso/del/file")
 
 ChiudeMagic(magic)
 
End


Private Procedure ChiudeMagic(mgc As Pointer)
 
 magic_close(mgc)
  
End


Riferimenti