Tmpfile ()

Da Gambas-it.org - Wikipedia.

La funzione tmpfile( ), dichiarata nel file header di sistema "/usr/include/stdio.h"

FILE *tmpfile (void)

crea un file temporaneo e lo apre in modalità binaria contemporaneamente in lettura ed in scrittura.

La funzione tmpfile( ) ritorna un Puntatore di tipo FILE *, dichiarato nella citata libreria standard "stdio.h", che in Gambas andrà opportunamente gestito con le medesime modalità previste per detto tipo di Puntatore creato con la funzione fopen( ). Si utilizzeranno, pertanto, le funzioni esterne fread( ), fwrite( ), fseek( ), etc. Il Puntatore, infine, andrà chiuso esclusivamente con la funzione esterna fclose().


Volendola utilizzare in Gambas, bisognerà dichiararla con Extern, nonché bisognerà dichiarare la libreria di C: libc.so.6, nella quale la funzione è contenuta:

Private Extern tmpfile() As Pointer In "libc:6"


Mostriamo un semplice esempio:

Library "libc:6"

Private Enum SEEK_SET = 0, SEEK_CUR, SEEK_END

' FILE *tmpfile (void)
' Create a temporary file and open it read/write.
Private Extern tmpfile() As Pointer

' size_t fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)
' Write chunks of generic data to STREAM.
Private Extern fwrite(ptr As String, size As Integer, nmemb As Integer, filestream As Pointer) As Integer
   
' int fseek(FILE *stream, long offset, int whence)
' Seek to a certain position on STREAM.
Private Extern fseek(streamp As Pointer, offset As Long, whence As Integer) As Integer

' size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
' Read chunks of generic data from STREAM.
Private Extern fread(ptr As Pointer, size As Integer, nmemb As Integer, streamp As Pointer) As Integer
  
' int fclose (FILE *__stream)
' Close STREAM.
Private Extern fclose(__stream As Pointer) As Integer


 Public Sub Main()
 
 Dim p As Pointer
 Dim s As string
 Dim i As Integer
 
  s = "Testo qualsiasi"
  i = Len(s)
  
  p = tmpfile()
  If p = 0 Then Error.Raise("Impossibile creare il file temporaneo !")
  
' Scriviamo il contenuto della stringa "s" nel Puntatore "p" creato.
  fwrite(s, i, 1, p)
  
' E' necessario tornare all'inizio dell'area puntata dal Puntatore "p":
  fseek(fl, 0, SEEK_SET)
  
' Leggiamo i dati dal Puntatore "p" creato e li scriviamo nel Puntatore "ris":
  ris = Alloc(SizeOf(gb.Byte), i)
  fread(ris, strlen(s), 1, fl)
  
' Leggiamo la stringa:
  Print String@(ris)   
  
' Liberiamo la memoria precedentemente occupata:
  Free(ris)
  fclose(p)
  
End



Riferimenti