Binary Files

Strings

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.

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.

“Weeks of coding can save you hours of planning.”