TechnologyUK - Programming (VB6) Logo

File Input and Output

Input is data sent to a program. It can be read from a file, or may be provided by the user from the keyboard. Output is data that is sent from the program to an output device. It may be displayed on the screen, written to a file, or sent to the printer. In this tutorial, we will be dealing input from, and output to, text files. Text files can be read from and written to by almost any kind of program. Before it can read or write file data, however, Visual Basic must open the file using the Open statement, as in the following code fragment:

Open strFileName [For Mode] As [#] intFileNumber

The strFileName value specifies the name of the file to be opened for reading or writing. If the file does not reside in the default directory, it will be necessary to specify the full path to the file in strFileName.

The Mode value must be one of the values in the table below, and specifies the type of operation (read, write or append) that is to be carried out on the file.

Visual Basic File Modes
Append Data will be written to the end of the file if it exists.
If the file does not exist, it will be created.
Input Data is to be read from the file. If the file does not
exist, Visual Basic generates an error message.
Output Data will be written to the file. If the file does not
exist, it will be created. If the file does already exist,
the existing file is deleted and a new file is created
to replace it.

The intFileNumber value represents a number between 1 and 255 that becomes the reference number for the open file. The file number stays with the file until it is closed. If another file is opened while the first file is still open, a different number must be used.

Reading Data from Files

Data can be stored in a simple ASCII text file. A file can hold one item per line, or a number of items on the same line, separated by commas. For example, in a file holding student register information for a particular class, each line could contain the name of a student and their student number, as shown below:

Contents of file "Students.txt"
"Stephanie Brown", 05342671

"Colin Casey", 05342664

"John Evans", 05342674

"Linda Hunter", 05342680

When data is retrieved from the file it will be read sequentially (in order), so the data items will be assigned to variables in the same order that they appear in the file. When a file is opened for reading (or writing), a reference number is assigned to the file between 1 and 255, which can then be used to direct subsequent read and write operations to the file. Visual Basic applications may be working with a number of open data files at any one time, so the reference number provides a means of uniquely identifying the individual files. The generic code below opens a file for input and reads an item of data into a variable.

Open strFileName For Input As #n
Input #n, var
Close #n

In the above code fragment, n is a number between 1 and 255 assigned to the file as a reference number. The term strFileName refers to the filename of the file to be opened, along with the directory path information that the program needs to locate the file. The Input statement reads in the next available item of data from the file and assigns its value to the variable var. Once the required data has been read from the file, the Close statement closes the file (note that the statement Close used on its own, i.e. without a reference number, closes all open files). Within a text file, individual items of data are separated by commas or line breaks. The variable in the Input statement should be of the same type as the data item whose value is to be assigned to it.

Example 1

Open a new Visual Basic project, save it to a new folder, and create a form similar to the one illustrated below (this form design will be used for all of the examples in this section).

The File I/O form

The File I/O Form Controls
ControlName CaptionAdditional Properties
Form Form1 File I/O  
Button cmdDisplay Display  
PictureBox picInput    

Create a text file containing the following lines, and save it as "Data.txt".

Contents of file "Data.txt"
 "Downing Street"

Attach the code shown below to the command button (cmdDisplay), run the program, and click on the command button to see the output.

Private Sub cmdDisplay_Click()
    Dim houseNumber As Single, street As String
    Open "Data.txt" For Input As #1
    Input #1, houseNumber
    Input #1, street
    picInput.Print "The Prime Minister lives at"; houseNumber; street
    Close #1
End Sub

The output is shown below.

The output from the program for Example 1

The program gets the first item of data from the file (10) and assigns it to the integer variable houseNumber. It then gets the next item of data ("Downing Street") and assigns it to the string variable street. Note that, if the file is not in the default program directory, you will need to include directory path information to tell the program where the file is. If it is located in the subdirectory "VB6"on the C drive, for example, the line should read:

Open "C:\VB6\Data.txt" For Input As #1

Example 2

A single Input statement can assign values to several different variables. To illustrate this, first create and save the text file "Students.txt" (see above), then change the code for the command button (cmdDisplay) as follows, and run the program:

Private Sub cmdDisplay_Click()
    Dim studentName As String, studentID As Long
    Dim Counter as Integer
    Open "Students.txt" For Input As #1
    For Counter = 1 to 4
        Input #1, studentName, studentID
        picInput.Print "Student name:"; studentName
        picInput.Print "Student number:"; studentID
    Close #1
End Sub

Click on the command button. The output from this program is shown below.

The output from the program for Example 2

Example 3

Sometimes, we need to read the data in a file more than once. This is accomplished by closing the file and then reopening it, which causes subsequent Input statements to begin reading from the beginning of the file again. Create another text file containing the following lines, and save it as "Sales.txt":

Contents of file "Sales.txt"
Devon, 9970

Cornwall, 6354

Somerset, 9768

Dorset, 5378

Avon, 15478

Now amend the code for the command button (cmdDisplay) as follows:

Private Sub cmdDisplay_Click()
    Dim Total As Long
    Dim County As String * 21, Sales As Integer
    Total = 0
    Open App.Path & "\Sales.txt" For Input As #1
    Do Until (EOF(1) = True)
        Input #1, County, Sales
        Total = Total + Sales
    Close #1
    Open App.Path & "\Sales.txt" For Input As #1
    Do Until (EOF(1) = True)
        Input #1, County, Sales
        picInput.Print County; Format(Sales / Total, "Percent")
    Close #1
End Sub

Run the program, and click on the command button (cmdDisplay). The output from the program is now as shown below.

The output from the program for Example 3

The program reads the data file once to calculate the total number of sales units achieved within each county. It then reads the file again to calculate the percentage of the total sales that is attributable to each county.

Looking at the code, you may have noticed some additional features that we have not previously used. For example:

Open App.Path & "\Sales.txt" For Input As #1

Here, the open command uses the function App.Path to return a string containing the directory path to the folder that contains the application. This causes Visual Basic to look for the data file "Sales.txt" in the directory containing the program.

The code also uses a slightly different loop construct to read the file data:

Do Until (EOF(1) = True)
    Input #1, County, Sales
    Total = Total + Sales

Although we know that there are five sets of value in the file to be read, this will not always be the case, especially with large files. If all the data items in a file have been read by Input statements, and a further Input statement attempts to read data from the file, a box will appear displaying the message:

"Input past end of file."

This error can be avoided by testing for the end of the file before attempting to read data using the built-in Eof() function in a Do ... Until loop, which returns True if the end of the file has been reached. If the number of records read needs to be known, a counter variable can be declared that will be incremented during each iteration of the loop.

Note also from the data file used here that a string within a text file does not need to be enclosed by quotation marks unless it contains commas, or leading and trailing spaces.

If an Input statement is expecting a string and finds a number, it will treat the number as a string. Conversely, if an Input statement is looking for a number and finds a string, it will assign a value of zero to the numeric variable.

Writing Data to Files

The Write command can be used to write data of any type to a file that has been opened in Output or Append mode, and is used as follows:

Write # intFileNumber [, ExpressionList ]

If the optional  ExpressionList is omitted, no values are written, but the carriage return and line feed character are sent to the file, creating a blank line therein. If more than one value is included in ExpressionList, the following considerations will apply:

The following statement writes three values to the file referenced by #1:

Write #1, intDaysHire, strLastName, strFirstName

The above statement is written as a single line of text to the file, and might appear something like the following:

7, "Bloggs", "Fred"

By default, each Write command places the file data on a separate line. Ending the Write with a semicolon (;) if you want the next Write to continue on the same line in the data file. The program listing below shows the amended procedure code for the command button (cmdDisplay). When the user clicks on the command button, the program reads the data from the "Students.txt" file, writes it to a second file ("Backup.txt"), and then displays the contents of the "Backup.txt" file.

Private Sub cmdDisplay_Click()
     Dim studentName As String, studentID As Long
     Dim Counter As Integer
     Open "Students.txt" For Input As #1
     Open "Backup.txt" For Output As #2
     Do Until (EOF(1) = True)
          Input #1, studentName, studentID
          Write #2, studentName, studentID
     Close ' closes all files
     Open "Backup.txt" For Input As #2
     picInput.Print "Here is the input from Backup.txt:"
     Do Until (EOF(2) = True)
          Input #2, studentName, studentID
          picInput.Print "Student name: "; studentName
          picInput.Print "Student number: "; studentID
     Close #2
End Sub

The output from the program now looks like this:

The output from the program that creates the file "Backup.txt"