tags:

views:

46

answers:

2

What's the fastest way (using VB6) to read an entire, large, binary file into an array?

+1  A: 

Here's one way, although you are limited to files around 2 GB in size.

Dim fileNum As Integer
Dim fileLength As Integer
Dim bytes() As Byte
Dim data As Byte
Dim i As Long

fileNum = FreeFile
Open "C:\test.bin" For Binary As fileNum
fileLength = LOF(fileNum)
ReDim bytes(fileLength)
i = 0
Do While Not EOF(fileNum)
  Get fileNum, , data
  bytes(i) = data
  i = i + 1
Loop  
Close fileNum
raven
Why loop? Just `Get fileNum, , bytes` and speed it up 100x
wqw
+1  A: 

You can compare these two

Private Function ReadFile1(sFile As String) As Byte()
    Dim nFile       As Integer

    nFile = FreeFile
    Open sFile For Input Access Read As #nFile
    If LOF(nFile) > 0 Then
        ReadFile1 = InputB(LOF(nFile), nFile)
    End If
    Close #nFile
End Function

Private Function ReadFile2(sFile As String) As Byte()
    Dim nFile       As Integer

    nFile = FreeFile
    Open sFile For Binary Access Read As #nFile
    If LOF(nFile) > 0 Then
        ReDim ReadFile2(0 To LOF(nFile) - 1)
        Get nFile, , ReadFile2
    End If
    Close #nFile
End Function

I prefer the second one but it has this nasty side effect. If sFile does not exists For Binary mode creates an empty file no matter that Access Read is used.

wqw