Binary file access
Binary access is the most basic way to read a file. It is called binary access
because you read the file byte by byte (letter by letter, character by character).
To open a file using Binary Access you simply say For Binary, instead of For
Input or Output etc. So,
Open App.Path & "c:\test.txt" For Binary As nFileNum
would open test.txt for binary access. To read characters from a file using
binary access, you use the Get statement, which uses the following syntax:
Get FileNumber, ByteNumber, DestinationString
So, you pass the file number that you opened the file with, the byte to start
at, and the string to put the result into. You will probably be wondering now
how you specify how long a string to get. For binary access, you simply fill
DestinationString with x number of spaces, where
x is the number of characters you want to retrieve. For example,
sMyString = Space(7)
Get #nFileNum, 12, sMyString
would get 7 characters from the file (because sMyString is filled with 7 spaces),
starting at byte 12 (the second parameter of Get). To write to a file using
binary access, you use the Get statement:
Get FileNumber, ByteNumber, DestinationString
The following code opens a file for binary access and fills TextBox1 with bytes
12-18 of the file.
Dim nFileNum As Integer, sMyString As String
' Get a free file number
nFileNum = FreeFile
' Open the file test.txt for binary access
Open "test.txt" For Binary As nFileNum
sMyString = Space(7)
' Read 7 characters from the file, starting at byte 12
Get #nFileNum, 12, sMyString
' Close the file
Close nFileNum
' Fill TextBox1 with the string
TextBox1.Text = sMyString