September 21, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Handling Files in Visual Basic

  • November 19, 2002
  • By Alex Allan
  • Send Email »
  • More Articles »

First off, let's take a look at the file modes input, output and append. You use these three types to read or write plain text - such as that found in .txt, .bat and .ini files.

But when should you use each mode? Well, it depends on what you want to do. Use the following list to help you decide...

  • The Output mode creates a blank file and allows you to write information into it.
  • The Append mode is similar to the Output mode but appends (adds to) an existing file.
  • The Input mode opens a file for reading.

Top Tip: You may hear these file modes being referred to as 'sequential files'. That's 'cause once you have read or written to a line, you can't go back to it unless you close and re-open. In other words, the modes are one way sequential.

So, for example, to open a file for output, you'd use the Open statement like this:

Open "c:\windows\faq.txt" For Output As #1

That's all fine and dandy, but how do you use each mode after youve opened the file?

To write to a file we use (Output and Append only):

Print #filenumber, expression

To read from a file we use (Input only):

Input #filenumber, variablelist

This probably looks completely confusing at the moment, so let's figure out what it all means.

Let's imagine you've opened a file for output, like this...

Open "c:\groovy\myfile.txt" For Output As #1

...we now want to put information into this file using the Print statement, like this:

Print #1, "Hello World!"

This inserts the information you pass it direct to the file in #1.

If you'd opened a file for Input, like this...

Open "c:\groovy\myotherfile.txt" For Input As #1

...you can read information from the file, like this...

Input #1, MyVariableName

This reads information from the file in #1 and puts it into your variable.

Let's use an example - it's easier to explain that way!

Building a Sample

Let's build a sample to demonstrate accessing files:

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

You should be left with a blank form.

  • Throw a simple Text Box onto the form
  • Go to the Properties window and change MultiLine to True
  • Create two Command buttons, setting the caption of the first to Read and the second to Write.

So far, it should look something like this:

Now, double-click on Read and insert the following code:

Private Sub Command1_Click()    'Outline:       - Asks the user for a file.    '               - Reads all the data into Text1.        Dim FilePath As String    Dim Data As String        FilePath = InputBox("Enter the path for a text file", "The Two R's", _    "C:\WINDOWS\WINNEWS.TXT")    'Asks the user for some input via an input box.        Open FilePath For Input As #1    'Opens the file given by the user.        Do Until EOF(1)    'Does this loop until End Of File(EOF) for file number 1.        Line Input #1, Data        'Read one line and puts it into the varible Data.        Text1.Text = Text1.Text & vbCrLf & Data        'Adds the read line into Text1.        MsgBox EOF(1)    Loop        Close #1    'Closes this file.End Sub

Read the comments (anything prefixed by an apostrophe).

Next, double-click on Write and insert the following code:

Private Sub Command2_Click()    'Outline:       - Asks the user for a file.    '               - Writes it all to a the file.        Dim FilePath As String        FilePath = InputBox("Enter the path for a text file", _    "The Two R's")    'Asks the user for some input via an input box.        Open FilePath For Output As #1    'Opens the file given by the user (for Output).        Print #1, Text1.Text    'Writes the data into the file number #1        Close #1End Sub

Once again, read all the comments. Do you understand what's happening?

Hit F5 to run your program!

Congratulations! You've just created a simple text editor. The Write button performs a simple 'Save As' whilst the Read button is the equivalent of 'Open'.

Didn't I Mention Those?

You may have noticed a few things in my code that I haven't told you about. Let's take a peek at a few geeky code words...

Line Input #filenumber, MyVariableName

- This is the same as Input but it reads the whole line instead of stopping at a comma (which can be useful - sometimes)

EOF(#filenumber)

- This outputs a true or false value, depending on whether it has hit the 'end' of the file. In my code, I used it in the DoLoop for Read. When EOF=True, the loop ends.

Close #filenumber

- This closes the file. It allows other files to open this file.

And if you'll be getting real friendly with files in Visual Basic, here are a few other file writing functions you may be interested in:

Write #filenumber, outputlist

This is similar to Print but it writes "screen formatted data" instead of raw data to a file. This means that values (numbers) have hashes ("#") put around them and strings have quote marks put around them. This makes the text less human readable but easier to read for your programs.

LOC(#filenumber)

The LOC function returns the current read/write position within an open file.

LOF(#filenumber)

The LOF function gives you the length of the file open.

FreeFile

This will give you next available file number.

Example:

MyFileNumber = FreeFileOpen "c:\windows\faq.txt" For Input as #MyFileNumber
Input$(number_of_chars_to_return, #filenumber)

This is the same as Input and Line Input except it has no limits (except the ones you set in number_of_chars_to_return). By using LOF - this can be used to get the whole file. We could replace all the stuff in the DoLoop in the Read button, with:

Text1.Text = Input$(LOF(1),#1)

Why not have a play around and see what these do? Go on, have a go!

That's about it for the Input, Output and Append modes. If you're thirsty for more, check out John Percival's article on Adding Lines to Autoexec.bat.





Page 2 of 6



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel