Tuesday, May 17, 2005

VB Helper: HowTo: Quickly read and write a binary file to and from an array

VB Helper: HowTo: Quickly read and write a binary file to and from an array:


Private Sub cmdWriteValues_Click()
Dim file_name As String
Dim file_length As Long
Dim fnum As Integer
Dim bytes() As Byte
Dim txt As String
Dim i As Integer
Dim values As Variant
Dim num_values As Integer

' Build the values array.
values = Split(txtValues.Text, vbCrLf)
For i = 0 To UBound(values)
If Len(Trim$(values(i))) > 0 Then
num_values = num_values + 1
ReDim Preserve bytes(1 To num_values)
bytes(num_values) = values(i)
End If
Next i

' Delete any existing file.
file_name = txtFile.Text
On Error Resume Next
Kill file_name
On Error GoTo 0

' Save the file.
fnum = FreeFile
Open file_name For Binary As #fnum
Put #fnum, 1, bytes
Close fnum

' Clear the results.
txtValues.Text = ''
End Sub


To read the file, open the file for binary access its length as its record size. Use Get to read the whole array at once.


Private Sub cmdReadValues_Click()
Dim file_name As String
Dim file_length As Long
Dim fnum As Integer
Dim bytes() As Byte
Dim txt As String
Dim i As Integer

file_name = txtFile.Text
file_length = FileLen(file_name)

fnum = FreeFile
ReDim bytes(1 To file_length)

Open file_name For Binary As #fnum
Get #fnum, 1, bytes
Close fnum

' Display the results.
For i = 1 To file_length
txt = txt & Format$(bytes(i)) & vbCrLf
Next i
txtValues.Text = txt
End Sub

0 Comments:

Post a Comment

<< Home