Getline ()

Da Gambas-it.org - Wikipedia.

La funzione getline(), dichiarata nel file header "stdio.h" come segue:

_IO_ssize_t getline (char **__restrict __lineptr, size_t *__restrict __n, FILE *__restrict __stream)

legge da un flusso di dati fino al valore "nuova linea a capo" (&h0A).

La funzione è, pertanto, utile per leggere una riga da un file (flusso) di testo.

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

Private Extern getline(__lineptr As Pointer, __n As Pointer, __stream As Pointer) As Long


Mostriamo di seguito un semplice esempio, nel quale si leggerà un testo (anche eventualmente comprensivo di spazi) dallo standard input:

Library "libc:6"

' FILE *fopen (const char *__restrict __filename, const char *__restrict __modes)
' Open a file and create a new stream for it.
Private Extern fopen(__filename As String, __modes As String) As Pointer

' _IO_ssize_t getline (char **__restrict __lineptr, size_t *__restrict __n, FILE *__restrict __stream)
' Read up to (and including) a newline from STREAM.
Private Extern getline(__lineptr As Pointer, __n As Pointer, __stream As Pointer) As Long

' int fclose (FILE *__stream)
' Close STREAM.
Private Extern fclose(filestream As Pointer) As Integer


Public Sub Main()
 
 Dim dest, p As Pointer
 Dim l As Long
  
  p = fopen("/dev/stdin", "r")
  
' Resta in attesa che si inserisca un qualsiasi testo nella console/Terminale, e si prema sul tasto "Invio":
  getline(VarPtr(dest), VarPtr(l), p)
  
  Print String@(dest)
  
  fclose(p)
  
End



Riferimenti