Binary Files

More Strings

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.

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Owning a computer without programming is like having a kitchen and using only the microwave oven” - Charles Petzold