Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 134,266 times

Contents

Related Categories

Binary Files - Strings

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.

James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.

Comments