February 28, 2021
Hot Topics:

Handling Files in Visual Basic

  • By Alex Allan
  • Send Email »
  • More Articles »

Now, scrap all you know about writing to text files. Yep, the methods of accessing random files are wildly different.

This method of writing to files I personally find a lot more useful. Instead of storing data in lines, random mode files are stored in records, just like an Access database stores its information.

Let's look at a sample of how we can open a file for Random access:

Open "c:\myfile.ran" For Random As #1 Len=1000

Here you can see that the file myfile.ran is being opened as a random file under the number 1. However, the more observant of you will notice there is an extra bit at the end - Len= - I'll explain what that does in a short while.

Firstly, we have to get the Random file format clear in our heads. You need to think of it as being like an Excel spreadsheet with only one column (the "A" column) and expanding for an infinite number of rows down. As with Excel each of these boxes can hold its own type of data. Let's take a good ol' peek at the diagram below:

This is how random files are stored and how you, as the developer, will access data in these files.

Next, we need to actually know how to read and write to these random files. For this we used the two commands:

Get #filenumber, recnumber, varname Statement
Put #filenumber, recnumber, varname Statement

You use Get to read data from your file and Put to write data to your file. For #filenumber you use the number that you used in the Open statement (e.g. #1), for the recnumber you put the record you'd like to access and the varname is the variable that you want to read into (Get) or write into (Put).

Once again, it's probably easier to demonstrate this with another sample!

And Another Sample!

Go through the following steps in order to build a sample application using the Random mode:

Open Visual Basic and double-click on "Standard EXE"

You will be left with a blank form.

Add two Text Box controls, two Command Buttons and a Check Box onto the form

Don't worry about naming conventions for now.

<Alex grins insanely>

Next, insert the following code into the (Declarations) code section of the Form.

Option Explicit'Forces us to declare our varibles.Private tmpText1 As StringPrivate tmpText2 As StringPrivate tmpCheck1 As Boolean'Declares temp varibles.Private Sub Command1_Click()    'Outline:   Launches this program.        If MsgBox("Click OK to run  " & Text1.Text, _vbOKCancel + vbQuestion, "The Open Statement") = _        vbCancel Then        'If the user clicked on 'Cancel'        Exit Sub    Else        'If the user clicked OK        Shell Text2.Text, IIf(Check1 = True, _        vbMinimizedFocus, vbNormalFocus)    End IfEnd SubPrivate Sub Form_Load()    'Outline:   - Opens the test file    '           - Opens records 1-3 into the controls.        Open "c:\test.ran" For Random As #1        If FileLen("c:\test.ran") = 0 Then CreateBlankFile    'If this file has just been created then run ' the sub 'CreateBlankFile'        Get #1, 1, tmpText1    Get #1, 2, tmpText2    Get #1, 3, tmpCheck1    'Gets all the values and puts them into ' the temp varibles.        Text1.Text = tmpText1    Text2.Text = tmpText2    Check1 = tmpCheck1    'Sets the values in the controls to the temp values.        End SubPrivate Sub Command2_Click()    'Outline:   Saves the current values.        tmpText1 = Text1.Text    tmpText2 = Text2.Text    tmpCheck1 = Check1    'Sets the temp values to the values in the controls.        Put #1, 1, tmpText1    Put #1, 2, tmpText2    Put #1, 3, tmpCheck1End SubPrivate Sub CreateBlankFile()    'Outline:   This creates a blank file.        tmpText1 = ""    tmpText2 = ""    tmpCheck1 = False    'Clears the temp varibles.        Put #1, 1, tmpText1    Put #1, 2, tmpText2    Put #1, 3, tmpCheck1    'Writes the varibles into the fileEnd Sub

Read all the comments here. Can you figure out what's happening?

Hit F5 to run the program!

Well done - you've just created a program launcher! Try it out. Does it work?

Top Tip: If you're using Visual Basic 4 or below, it's probably time to upgrade. Oh, and you'll also have to declare any variable and constants before writing them to a file (using the Dim statement).

What's What?

Let's run over a few particulars of the code that'll be of interest. Well, maybe.

  • You may notice that I used a few temporary variables (tmpText1, tmpText2 and tmpCheck1) to store data in before I read or wrote data into the controls. This is because Get and Put are very picky about the data they read or write. Data for Get and Put must not come directly from form controls or user defined types.

FileLen outputs the file size in bytes. So, if LenFile(1) in our code equals 0 then the Open statement has just made the file. Therefore, we will need to create this file using our CreateBlankFile subroutine.

IIf(expression, truepart, falsepart)

See John Percival's IIf Tip function

But what about that 'Len=' mystery I promised to unravel for you?

Let's think about this in terms of an Excel Spreadsheet. Think of each cell having a maximum size. This maximum size is set (in bytes) in the Len= section of the Open statement (by default it's 256 bytes).

Unfortunately, as with everything else in life, size matters. So there is a drawback in setting a huge length using 'Len ='. Try out the following code:

Open "c:\test.ran" For Random As #1 Len=10240Put #1,1000,"Hello"Close #1

The results aren't pretty. You will end up with a file which is about 10MB. Why? Because you created a record at the point 1,000. Now, Visual Basic must leave space to put records before record 1,000 it will create a bundle of blank records from 1 to 999, each taking up 10,240 bytes. So, this leaves a file that is:

10,240 bytes x 1,000 records = 10,240,000 bytes

so, that's 10,240,000 / 1048576 (that's how many bytes there are in a megabyte) which equals 9.77MB

So be careful - you have been warned!

But anyway, enough calculations. Let's think about how we can take our work one step beyond.

Improved Example - I've updated the example to include support for many applications. This is more useful because it stores many applications. You can download it here.

I've made a module for use with VB that treats random mode files in sets of data. Each data set has a name. This works perfectly with the improved example mentioned above so you can spend less time coding monotonous Get and Put commands. You can download this one here.

To help you programming you can use this Excel spreadsheet (with macros) to read and output your random mode files.

Page 3 of 6

This article was originally published on November 20, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date