Of course, the method on the last page is not particularly useful, as we often don't know the length of the string we are going to write. We work around this by writing the length of the string to the file, before writing the actual string. Because, as we saw earlier, we don't need to know the number of digits in the number (so long as we know the datatype), this method works.
So, when writing to a file, we first measure the length of the string using Len, and output the length, and then the string:
Dim nFileNum As Integer
Dim nLen As Integer, sString As String
nFileNum = FreeFile
Open App.Path & "example.bin" For Binary Access _
Write Lock Read Write As #nFileNum
'fill the string
sString = "Our sample string"
'get the length of the string
nLen = Len(sString)
'output them both...
Put #nFileNum, , nLen
Put #nFileNum, , sString
Close #nFileNum
and then, to read the value, we read the length first:
Dim nFileNum As Integer
Dim nLen As Integer, sString As String
nFileNum = FreeFile
Open App.Path & "example.bin" For Binary Access _
Read Lock Read Write As #nFileNum
'read the length of the string
Get #nFileNum, , nLen
'initialize the string with the correct number
'of spaces
sString = Space$(nLen)
Get #nFileNum, , sString
Close #nFileNum
Msgbox sString
You will notice that this time we don't specify a byte to read or write to. This is because, although we don't need to know the length of the number we write, the value for sString doesn't necessarily start as byte 2. Instead, we simply leave this parameter blank, and VB will automatically move to the start of the next part of the data for when we call the next Get statement. This makes it far easier than worrying about the position of the individual bytes, provided that we always read and write the variables in the same order. If you try to read a variable that was written last, first, then you will be in trouble.
Comments