Visual Basic - Read Variables from and into files

tboneuls

Banned
Nov 17, 2001
384
0
0
How would i go about writing variables to a file and later using those variables again by reading them from the file? Thanks in advance.
 

VBboy

Diamond Member
Nov 12, 2000
5,793
0
0
You don't read "variables" from a file. You can read their values. The easiest way is to store them one per line (but you can also do comma-separated values, which won't work with strings containing commas).

This is such a general question that you should look up help on the following functions:

"Open" and "Input" as well as "Line Input" on MSDN.microsoft.com or just on Google.

If you want a higher-level facility, you can do .Ini-file style saving and loading of data but it is much more involved.
 

VBboy

Diamond Member
Nov 12, 2000
5,793
0
0
But ok, here is an example.

Dim lVariableOne As Long
Dim sVariableTwo As String

lVariableOne = 12345
sVariableTwo = "Blah"

Dim lFileNum As Long
Dim sFileName As String

lFileNum = FreeFile
sFileName = "C:\FileToSaveTo.txt"

Open sFileName For Output As #lFileNum
Print #lFileNum, lVariableOne
Print #lFileNum, sVariableTwo

Close #lFileNum
 

calpha

Golden Member
Mar 7, 2001
1,287
0
0
The laziest way to use Variables & flat file is w/ a UDT

Dim Type MyType

'declarations
End Type

Dim udtMyType as MyType

'open file stuff....binary if I remember right

print #<filenum>, udtMyType

And that will print out the whole UDT in one shot. Then you can read straight from the file into another UDT......keeps you from having to separate out everything after you delcare your UDT.
 

VBboy

Diamond Member
Nov 12, 2000
5,793
0
0
calpha, you can't Dim Type MyType. It was probably a typo, though. You need to do Type MyType..
 

calpha

Golden Member
Mar 7, 2001
1,287
0
0
Originally posted by: VBboy
calpha, you can't Dim Type MyType. It was probably a typo, though. You need to do Type MyType..

Yah, it was.

Just typed it straight the post window. Good Catch.