When writing to a binary file, we use the Put statement. This takes the form
Put #FileNumber, ByteNumber, VariableName
FileNumber is the file number we used to open the file, ByteNumber is the position that we should start writing the data, and VariableName is the variable/string containing the data we want to write.
As a simple example, we'll output a new file, with its first byte set to 1:
Dim nFileNum As Integer
nFileNum = FreeFile
Open App.Path & "example.bin" For Binary Access _
Write Lock Read Write As #nFileNum Read Write As #nFileNum
Put #nFileNum, 1, 2 'outputs the value 2 to byte 1
Close #nFileNum
We now need to find out how to read this value back. In VB, we do this using the Get statement, which takes the same form as Put:
Get #FileNumber, ByteNumber, VariableName
except that this time the value at ByteNumber will be read into VariableName. Notice that we don't specify the number of bytes we want to read. When using Binary files, this is done by setting the length of VariableName to the length of data we want to read.
If we have written to a file, an integer value of 1, the VariableName needs to have a datatype of Integer. Whether we write 4 numbers or only 1, VariableName will always be filled with the correct value. Lets take a look at this using another example. The code below will read the value from the file we created in the previous example.
Dim nFileNum As Integer, nNumber As Integer
nFileNum = FreeFile
Open App.Path & "example.bin" For Binary Access _
Read Lock Read Write As #nFileNum
Get #nFileNum, 1, nNumber
Close #nFileNum
Msgbox nNumber
If you execute the first example, and then the code above, you will get a message
box with the number 2 (the value we wrote to the file). Now, try changing thePut #nFileNum, 1, 2
line toPut #nFileNum, 1, 25432
and try executing the first, and then the second batch of code, you might
expect to only get 2 returned, as this is the first number we wrote. However,
what we actually receive is a message containing 25432
! This is
one of the great things with binary access... if you output a number or data
structure, it doesn't matter how long the items are in it, VB will always return
the correct length.
Comments