Reads data from a file to a buffer
Syntax
Usage
Get #filenum, position, data [, amount]
varres = Get (#filenum, position, data [, amount])
Parameters
filenum
The value passed to
Open when the file was opened
position
The position where the read must start. If the file was opened For Random, the position is in records; otherwise, it is in bytes. If omitted, read starts at the present file pointer position. The position is 1 based: the first record or byte of a file is at position 1.
data
The buffer where data is written. It can be a numeric variable, a string, an array, a user defined type or a dereferenced pointer. The read operation will try to fill completely the variable, unless
amount is given or the
EOF is reached. Note: If you want to read values into a buffer, you should NOT pass a pointer to the buffer; instead you should pass the first variable in the buffer. (This can be done by dereferencing the pointer with
Operator * (Value Of).) Get will automatically infer that the rest of the buffer continues after the first variable. If you pass a pointer, then
Get will overwrite the pointer, not the memory it points to.
amount
Limits
Get to read read
amount * SizeOf(datatype) bytes of data. If
amount is omitted it defaults to 1, and
Get reads one variable of the buffer's data type.
Return Value
0 on success; nonzero on error.
Description
Reads binary data from a file to a buffer variable
Get can be used as a function, and will return 0 on success or an error code on failure.
For files opened in
Random mode, the size in bytes of the data to read must match the specified record size.
Example
Dim buffer As Integer
Dim an_array(0 To 9) As Integer
Dim pmem As Integer Ptr
Dim f As Integer
Dim x As Integer
' Find the first free file file number.
f = FreeFile
' Open the file "file.ext" for binary usage, using the file number "f".
Open "file.ext" For Binary As #f
' Read 4 bytes from the file into buffer, using file number "f".
Get #f, , buffer
' print out result
Print buffer
' Read 40 (10 * 4) bytes from the file into an_array, using file number "f".
Get #f, , an_array()
' print out result
For x = 0 To 9
Print an_array(x)
Next
' allocate memory for 5 integers
pmem = Allocate(5 * SizeOf(Integer))
' Read 5 integers from the file into allocated memory
Get #f,, *pmem, 5 ' Note pmem must be dereferenced (*pmem)
' print out result using [] Pointer Indexing or pointer arithmic
For x = 0 To 4
Print pmem[x] ; *(pmem + x)
Next
' Close the file.
Close #f
End
' Load a small text file to a string
Function LoadFile(f As String) As String
Dim h As Integer
Dim txt As String
h = FreeFile
Open f For Binary Access Read As #h
If LOF(h) > 0 Then
txt = String(LOF(h),0)
Get #h,,txt
End If
Close #h
Return txt
End Function
Dim ExampleStr As String
ExampleStr = LoadFile("smallfile.txt")
Print ExampleStr
Differences from QB
- GET can read full arrays as in VB or, alternatively, read a multiple of the data size into the memory.
- GET can now be used as a function.
See also