Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleQuickly read and write a binary file to and from an array
Description
Keywordsbinary data, array, read, write, file
CategoriesFiles and Directories, Tips and Tricks
 
To write the file, open the file for binary access giving the number of bytes in the array as its record size. Use Put to write the whole array at once.
 
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
 
The original version of this program specified a "Len =" clause in the Open statements like this:

    Open file_name For Binary As #fnum Len = num_values
    ...
    Open file_name For Binary As #fnum Len = file_length

Thomas pointed out the following:

Note: MSDN says, mode Binary does not care about "Len = ...".

But actually VB6 does somehow care, so if you try to load a file > 32 KB with above method, an overflow runtime error will appear.

You should remove "Len = num_values" and "Len = file_length" from the example.

Thanks Thomas!
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated