Creare un file e scrivervi dati con le funzioni esterne della libreria libgio

Da Gambas-it.org - Wikipedia.

Possiamo utilizzare alcune funzioni esterne del API di GIO, per creare un file e scrivere al suo interno dei dati.

E' necessario avere installata nel sistema e richiamare in Gambas la libreria condivisa: "libgio-2.0.so.0.7200.4 "

Mostriamo un esempio pratico:

Library "libgio-2.0:0.7200.4"

Private Enum G_FILE_CREATE_NONE = 0, G_FILE_CREATE_PRIVATE, G_FILE_CREATE_REPLACE_DESTINATION

' GFile * g_file_new_for_path (const char *path)
' Constructs a GFile for a given path.
Private Extern g_file_new_for_path(path As String) As Pointer

' GFileOutputStream * g_file_create (GFile *file, GFileCreateFlags flags, GCancellable *cancellable, GError **error)
' Creates a new file and returns an output stream for writing to it.
Private Extern g_file_create(gfile As Pointer, flags As Integer, cancellable As Pointer, gerror As Pointer) As Pointer

' gssize g_output_stream_write (GOutputStream *stream, const void *buffer, gsize count, GCancellable *cancellable, GError **error)
' Tries to write count bytes from buffer into the stream. Will block during the operation.
Private Extern g_output_stream_write(gstream As Pointer, buffer As Pointer, count As Long, cancellable As Pointer, gerror As Pointer) As Long

' gboolean g_output_stream_close (GOutputStream *stream, GCancellable *cancellable, GError **error)
' Closes the stream, releasing resources related to it.
Private Extern g_output_stream_close(gstream As Pointer, cancellable As Pointer, gerror As Pointer) As Boolean

' void g_object_unref (gpointer object)
' Decreases the reference count of object.
Private Extern g_object_unref(gobject As Pointer)


Public Sub Main()
 
 Dim gf, os As Pointer
 Dim testo As String
 Dim l As Long
 Dim bo As Boolean
  
' Imposta il percorso e il nome del file da creare:
 gf = g_file_new_for_path("/tmp/test")
 If gf == 0 Then Error.Raise("Errore !")
  
' Crea il nuovo file:
 os = g_file_create(gf, G_FILE_CREATE_NONE, 0, 0)
 If os == 0 Then Error.Raise("Errore !")
 
 testo = "Gambas"

' Scrive n dati nel file:
 l = g_output_stream_write(os, testo, Len(testo), 0, 0)
 Print "Byte scritti nel file: "; l
  
' Chiude il flusso di dati del nuovo file:
 bo = g_output_stream_close(os, 0, 0)
 If Not bo Then Error.Raise("Errore !")
  
' Libera la memoria precedentemente occupata da GIO:
 g_object_unref(os)
 g_object_unref(gf)
  
End