Outputting and reading strings to a file is slightly different - in this case we do need to know how long the data is. So, if we output
Put #nFileNum, 1, "hello"
we need to know that the string we wrote was 5 characters in length to retreive the correct value again. First of all, lets assume that we do know this. How can we tell VB that the string is 5 characters in length, as there is no Length parameter for the Get statement?
What we do is initialize the string variable that we pass to Get beforehand, with the number of bytes we want to read. We normally do this using the Space$ function. For example,
sString = Space$(5)
fills sString with 5 spaces. Now, when we pass sString to the Get function, we retreive 5 characters. Try it! First, use
Dim nFileNum As Integer
nFileNum = FreeFile
Open App.Path & "example.bin" For Binary Access _
Write Lock Read Write As #nFileNum
Put #nFileNum, 1, "hello"
Close #nFileNum
to write the data to a file, and then use
Dim nFileNum As Integer, sString As String
nFileNum = FreeFile
Open App.Path & "example.bin" For Binary Access _
Read Lock Read Write As #nFileNum
sString = Space$(5)
Get #nFileNum, 1, sString
Close #nFileNum
Msgbox sString
to read the value back again.
Comments