0% found this document useful (0 votes)
50 views

Lesson XVIII:: Sequential File Handling

This document provides instruction on sequential file handling in Visual Basic. It covers opening and closing files, writing to files using the Write statement, and reading from files using the Input statement. It also discusses detecting the end of a file using EOF() and storing file contents in arrays. An example program is provided to demonstrate adding names to a list box from a text file on form load, and saving the list box contents to a text file when a button is clicked. Learners are tasked with modifying the program to include a student's name and age in the file, and adding functionality for deleting, editing, and browsing student records.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Lesson XVIII:: Sequential File Handling

This document provides instruction on sequential file handling in Visual Basic. It covers opening and closing files, writing to files using the Write statement, and reading from files using the Input statement. It also discusses detecting the end of a file using EOF() and storing file contents in arrays. An example program is provided to demonstrate adding names to a list box from a text file on form load, and saving the list box contents to a text file when a button is clicked. Learners are tasked with modifying the program to include a student's name and age in the file, and adding functionality for deleting, editing, and browsing student records.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 4

Lesson XVIII:

Sequential File Handling

Objectives
To be able to open and close sequential files using Open and Close
To be able to detect end-of-file condition
To be able to write to files using Write
To be able to fetch data from files using Input
Notes
Visual Basic offers file handling capabilities and database handling features. In database handling
controls, the file manipulation is transparent to the programmer and user. However, in nondatabase applications the programmer has to handle virtually all aspects of reading or editing the
data contained in a file. This is what this lesson will cover.
Simple text files (also called sequential files) are often used as the storage method for information.
This is because of their universally standard format. You can simple create text files using DOS
EditTM program and the newer Windows NotePadTM applications.
To start manipulating files, you must first open it. You do this through the following:
Open <filename> for <mode> As # <filenumber>
Close #<filenumber>
Open tells Visual Basic to locate a file specified by <filename>, open it for some purpose, and in
some cases, create the file if it does not exist. <filename> can be a string literal such as
D:\myfiles\names.txt or a string variable containing the name of the file to be opened. <mode>
tells Visual Basic what to do with the opened file. It can be any of the following:
Mode
Input
Output
Append
Random

Description
Opens files for reading. An error occurs if the specified file
does not exist.
Opens files for writing. If the specified file does not exist, VB
creates the file for writing. Note: It overwrites the contents
of the file specified.
Opens files for appending. It appends new data to the
contents (if there are any) of a file. If the specified file does
not exist, VB creates the file.
Opens files for reading or writing.

The pound sign (#) is optional. The <filenumber> value (also called file channel), which can be
between 1 and 255 inclusive, represents the specified file. If you need to manipulate a file, you
refer to the file by the <filenumber> to which it is associated. The number remains associated to
the file until such the time when you close the file using Close statement. Always remember that a
<filenumber> can only be associated to one file only at one time. If the file is closed, you may use
the <filenumber> again for some other file. If you have lost track of the available <filenumber>,
you may use the FreeFile() function as in the following statement:
FileNum = FreeFile()
The Close statement on the other hand performs the opposite job from Open. It closes a file and
releases the <filenumber> for reuse by the Open statement. There are 2 ways in which you can
use this statement. They are as follows:
Close #<filenumber>, , #<filenumber>

e.g.

Close #1

Close #1, #2, #7

Close
The first Close format closes one or more files as specified by the <filenumber>.
format close all opened files, thereby releasing all <filenumber>s.

The second

IN FOCUS: WRITING TO FILES


The Write command writes data of any data type or format to an opened file. You need to open a
file for Output, Append, or Random before you can use Write. Below is the syntax of Write:
Write #<filenumber>, <expressionlist>
<filenumber> is the number of the opened file where we will write the data. <expressionlist>
contains the value or values that you will be writing to the file.
If you dont specify
<expressionlist>, then Write writes a carriage return (ASCII 13) and line feed (ASCII 10) character
to the file. If you have multiple values in <expressionlist>, separate these values by a comma. VB
automatically writes a carriage return (ASCII 13) and line feed (ASCII 10) character after these data.
Lets take the following example:
StudeName(0) = Antonio
StudeName(1) = Heidi
StudeName(2) = Joni
StudeAge(0) = 24
StudeAge(1) = 25
StudeAge(2) = 29
Open C:\studerec.txt For Output As #1
For x = 1 To 2
Write #1, StudeName(x), StudeAge(x)
Next x
Close #1
When executed, the above code will produce the following file contents:
Antonio, 24
Heidi, 25
Joni, 29
IN FOCUS: READING FROM FILES
File handling does not only mean writing to files. What are files for if we do not use the contents?
Retrieving files is easy. You do this using the Input statement through the following syntax:
Input #<filenumber>, <expressionlist>
The Input statement reads the data stored in the file into a list of variables enumerated in
<expressionlist>. Note that the <expressionlist> should match the type and number of data
stored in the file. In our example above, we wrote the name followed by the age of the student. If
we fetch these data, a sample code might be:
Open C:\studerec.txt For Input As #1
Input #1, StdName, StdAge
Close #1
Variable StdName will receive the name while StdAge will receive the age. Thus, they must be of
type String and Integer respectively. More, the order of the variables in the <expressionlist>
should match the order of data in the file. The first value will be stored in the first variable, the
second value on the second variable, and so on. Errors may occur if read more data than the file
holds or when you are storing a data to a variable of incompatible type (e.g. a Boolean value into
an Integer variable).
We are not done yet. What the code above does is simply to fetch the values on the first line: store
Antonio to StdName and 24 to StdAge. From this, we say that Input just fetches one line only. So
do we fetch the remaining data? Answer: We need to do a loop through the file until we reach the
end of it. How do we know that we have reached the end of the file? Answer: VB provides you with
the EOF() function. It returns True if we have reached the End Of File. Therefore, what we should
do is to keep on executing Input while EOF() returns False. The following code does all these
routines:
Open C:\studerec.txt For Input As #1
Do Until (EOF(#1) = True)
Input #1 StdName, StdAge
Loop

Close #1
This code works but with one flaw: Every time we iterate the Input statement, we overwrite the date
previously stored in StdName and StdAge. This does not serve our purpose, after all! What we
should do then is to store the contents in an array.
Open C:\studerec.txt For Input As #1
x=0
Do Until (EOF(#1) = True)
Input #1 StdName(x), StdAge(x)
x=x+1
Loop
Close #1
After 3 iterations, we will have the following data:
StdName(0)
StdAge(0)

Antonio
24

StdName(1)
StdAge(1)

Heidi
25

StdName(2)
StdAge(2)

Joni
29

Lesson in Action
Lets create a simple file handling application. The Form below contains a TextBox, a ListBox and
2 CommandButtons. The Add Name button adds the name entered in the TextBox to the
ListBox. Save to File button saves the contents of the ListBox in a text file for future use.

Enter the following code into the code window.


This procedure adds the name in the TextBox in the ListBox
Private Sub cmdAddName_Click()
lstNames.AddItem txtName.Text
End Sub
This procedure saves the contents of the ListBox to a text file named names.txt
Private Sub cmdSave_Click()
Open App.Path & "\names.txt" For Output As #1
For x = 0 To lstNames.ListCount - 1
Write #1, lstNames.List(x)
Next x
Close #1
End Sub
When the form is loaded, this procedure retrieves the names saved in the file (if any)
Private Sub Form_Load()
Open App.Path & "\names.txt" For Input As #1
While Not EOF(1)
Input #1, temp
lstNames.AddItem temp
Wend
Close #1
End Sub

On your Own
Instructions: Modify the sample program to include not just the name but also the age of the
person. The program should also be able to delete a person and edit a persons data.

The < and > buttons are for browsing through the student records. When > is pressed, the
program displays the records of the next student (if any). Disable this button when there are no
more succeeding records. When < is pressed, the program displays the records of the previous
student (if any). Disable this button when there are no more preceding records. The records of
the first student (the one stored at index 0 of the array), if any, should be displayed during startup. The TextBoxes containing the students name and age should be locked to avoid being
edited. Unlock these TextBoxes only when the user adds a new student (when the New button is
pressed) or when the Edit button is pressed. Disable Edit and Delete buttons when there are no
displayed records. The Save button should be disabled until the user adds a new student
record. Use two arrays StudeName() and StudeAge() to store the students data and store these
in StudeRec.txt.

You might also like