11

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

2 Answers 2

16

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

  Dim fileNum As Integer
  Dim bytes() As Byte

  fileNum = FreeFile
  Open "C:\test.bin" For Binary As fileNum
  ReDim bytes(LOF(fileNum) - 1)
  Get fileNum, , bytes
  Close fileNum
Sign up to request clarification or add additional context in comments.

3 Comments

Why loop? Just Get fileNum, , bytes and speed it up 100x
On the Get fileNum, , data I get a Run-time Error 458, Variable uses an Automation Type not supported in Visual Basic. Any idea what's going on? Am I missing a library reference?
OK. Got it! Change it into this: ReDim bytes(1 To lenF) As Byte. Apparently I was using Variant and it didn't like it at all...
7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.