Writing Data to binary file

Here is example code that writes out a sequence of numbers to a binary file, and then reads them back in. Note: when using this code, the user needs to edit the location of the file defined in the 2nd line.

Dim bDir As String, fName As String, fPath As String
    bDir  = "C:\Users\Tom\Desktop\Temp\"
    fName = "binaryFileTest.dat"
    fPath = bDir & fName

    Open fPath For Binary Access Write As #1

    Print "Entry" & Chr(9) & "Random Number"
    Dim numVals As Long, curVal As Long
    Dim dNum As Double
    numVals = 15
    For curVal = 1 To numVals
        ' get a random number
        dNum = Rnd()
        Print curVal & Chr(9) & dNum

        ' write to file
        Put #1, , dNum


    Close #1

    ' Now, try and read values back out of the file
    Print "Entry" & Chr(9) & "Read Value"
    Open fPath For Binary Access Read As #1
    For curVal = 1 To numVals
        Get #1, , dNum
        Print curVal & Chr(9) & dNum
    Close #1 

Still need help? Contact Us Contact Us