CIS 230, Visual Basic
Ch. 10 Notes, page 1
Objective #1: Create data files.
- Many programming applications require data to be stored and updated between executions.
To store this data, we use data files. Often, they are called "external files"
since they do not contain executable code that makes the program run. Data files
contain information that is made up of records which can be accessed (i.e. read)
or modified (i.e. written to) by VB programs. Generally, three types of
data files are used in VB: sequential, random access,
and binary. We will not study binary files in this course.
- To create a data file, you can use any text-editing or word-processing application.
Carefully type the necessary data and save the file with a .txt or
.dat extension so that other applications and people will recognize the file as a
data text file. Often, NotePad or WordPad is used to
create a data file. These programs can usually be found in the Accessories folder on any
Windows PC.
- A file must be opened from within Visual Basic before it is can be used by the program
in any way. To open a file use the Open statement. The general form of
the Open statement is:
Open "FileName" For {Input | Output | Append |
Random} As #FileNumber [Len = RecLength]
where FileName stands for the actual filename of the file. An absolute DOS directory path
should be included as a string literal or a string expression amounting to the same.
Examples:
- Open "C:\HighScores.txt" For Input As #1
opens a file named
"HighScores.txt" that is located in the root C directory. It is being opened for
input which means that the data that is already in the file can be read
and used by the VB program. The #1 is the file number that the programmer
decided to use in the VB program to refer to HighScores.txt. Usually the first data file
that is opened is labelled #1 for convenience. If more than one file is opened by a VB
program at once, file numbers must be unique. If a file named "HighScores.txt"
cannot actually be found in the current directory, an error message will occur. The file
number simply marks the channel through which VB will communicate with the particular
file.
- Open "A:\Names.dat" For Output As #2
opens a file named "Names.dat" that is located on a floppy disk since it is
common for the A: drive to be the drive label for a floppy drive on PC's. In this case the
file is being opened for output which means that the VB program can write
data to that file. Anytime that a file is being used by a VB program, a file pointer marks
the current active location in that file. In the case of a sequential file being opened
for output, the file pointer points to the beginning of the file so the
first piece of data that is written to the file will be overwritten. If a sequential file
is opened for output, you cannot read from the file at the same time without closing it
first and reopening it for input.
- Open "C:\Temp\Data.txt" For Append As #3
opens a file named "Data.txt" that is located in the Temp directory on the
computer's hard drive (since C: commonly refers to a PC's primary hard drive). It is
typical for PC programmers to store files in a computers C:\Temp folder. This file is
being opened in Append mode which means that the file pointer initially
points to the end of the file and will allow the VB program to write new data to the file
without overwriting previously existing data. You cannot read data from a sequential file
that has been opened in Append mode.
- Open "StudentData.dat" For Random As #4 Len = 50
opens a file named
"StudentData.dat" as a random access file. The previous
examples were all sequential files. Random access files can be read from
or written to (i.e. are open for input and/or output) by the VB program. The Len = 50
indicates that the record size for each record is fixed as 50 bytes. This
size must be specified so that VB knows where to read or write data when the programmer
accesses records at random. (Even though the Len function returns the number of characters
in a string, it returns the number of bytes in a user-defined type variable, where
characters in a string are counted as 1 byte each.)
- You can create a data file from within a VB application, as well. Using the Open
statement will automatically create a file with the given name as long as it is not
being opened in Input mode. Make sure that you have chosen a unique file
name or another previously created file could accidentally be overwritten.
- Each file used in a VB program must be given a file number as described above. It is
convenient to use small counting numbers 1, 2, 3, etc. as file numbers. If you are not
sure what the next available integer is at a point in a program, you can use the
FreeFile function to assign the next lowest number to a newly opened file. The
statement Open
"C:\Temp\Next.dat" For Output As FreeFile would
assign the smallest available file number to the data file Next.dat. However, it would be
wise to first assign the number generated by the FreeFile function to a variable which
could be used later in the program with the given file as in:
intFileNumber = FreeFile
Open "C:\Temp\Next.dat" For Output As #intFileNumber
Objective #2: Read and write records to a disk.
- For sequential files, you use the Input # statement
to input comma-delimited data from an external data file.
- For each open sequential file, VB associates a file pointer with the file. The file
pointer begins by marking (i.e. pointing to) the first character in the data file. To read
the contents of the first line and to store them into a string variable named strWord,
this statement can be used: Input #1,
strWord The file number #1
is necessary to indicate the file that is to be read since more than one file may be
opened for input at a given time. The first piece of data will be stored in the string
variable strWord. Commas are used to delimit records in sequential access files. The file
pointer would then point to the next piece of data on the same line if a comma was
present. Otherwise the file pointer would point to the first byte or character on the next
line of the data file.
- For sequential files, you should use the Write # statement
to output data to a file in the form of records of varying lengths. (The Print # statement
can be used as well but is more suited for writing display formatted data.)
- For each open sequential file, VB associates a file pointer with the
file. If the file was opened for output, the file pointer started by pointing to the first
byte of the file. Therefore, to overwrite anything that happened to be on the first line
of a file with the string "Hello", you would use a statement like:
Write #1,
"Hello" if the file was
opened as file number 1. The statement Write
#1, "Hello", "world" would cause
the first line of the sequential file to be
"Hello","world" where the comma serves as a
delimiter between fields. The carriage return, Chr(13), and new line, Chr(10), characters
are read by the Input # statement but are not saved into the receiving variable. They are
discarded.
- To find the end of a sequential data file, it is convenient to use the EOF
function. At the end of every file, an EOF character (or mark) is used to
indicate the actual end. The following code excerpt could be used to assign each record of
a sequential file to separate items of a combo box:
Do Until EOF(1)
Input #1, strNext
cboSample.AddItem strNext
Loop
The loop continues until EOF(1) is true. EOF(1) is true as soon as file number #1 would
read the EOF character as the next character.
Objective #3: Determine the appropriate locations for data file-related code.
- Since we did not study Ch. 9, you will not be responsible for this objective.
Objective #4: Understand the significance of a Close statement.
- It is always a good idea to close any data files that were opened by a
VB program before it ends. To close a specific file previously opened as file number 1,
use the statement Close #1
. To close two files opened as file numbers 1 and 2, the statement Close #1, #2 can be used. To
close all open files at once, simply use Close
.
- While a VB program could end without specifically closing any external data files that
it used, this is considered bad practice. You could lose certain changes to those files or
you could even damage a file to a point where it can no longer be opened.
Objective #5: Differentiate between sequential and random files.
- Sequential files store text data that is separated into records.
Records on the same line are separated by commas however carriage return & new line
characters separate records on consecutive lines.
- Random access files store text data that is separated into records as
well however each record must be the same size. Within the structure of the record, any
number of fields can be used to separate different data types.
- A sequential file is used like an audiocassette tape. Data must
be accessed in order from the first piece through to the last.
- A random access file is used like an audio CD-ROM. Any piece of
data can be accessed at any time without necessarily accessing every piece of data that
happens to be located closer to the beginning of the file.
- Random access files usually require that you create and declare a user-defined data type
in the general declarations section of a form module.
- The advantages of random access files are that it is fast to locate data. Also, it may
be easier to update code written to work for random access files. The advantages of
sequentail files are that they are only use the space required by the actual number of
bytes present in the file.
Objective #6: Trap user errors and handle errors to avoid run-time errors.
- You will not be responsible for this objective this semester.
Objective #7: Incorporate fixed-length strings into user-defined data types.
- String variables can be declared to be dynamic or fixed-length.
- A dynamic string variable is simply declared with a statement such as:
Dim strName As String
where strName can hold as many characters as desired. It can also change in size
throughout the program.
- It is possible to declare a string variable to hold a maximum number of characters. The
declaration statement Dim
strName As String * 20 declares
a fixed string variable strName to a size that it can only hold 20
characters. If an attempt is made to assign a string that is longer than 20 characters to
strName, the original string will be truncated and only its first 20 characters will
"fit" into strName. On the other hand if a string with less than 20 characters
is assigned to strName, then blank spaces will be used to pad the string at the tail end.
Objective #8: Read and write objects in a random file.
- To read or write objects in a random file, the file must be opened in random
access mode.
- When a file is opened in random access mode, a record size is requested. This allows VB
to write or read specific records of the file without necessarily reading or writing all
of the previous data.
- Use the Put command to write data to a random access file. The general
form for the Put statement is: Put
[#]FileNumber, [RecordNumber], RecordName
. Examples:
- Put #1, 3, mudtStudentRecord
this statement writes the whole contents of the variable mudtStudentRecord to the third
record of the random access file #1.
- Put #2, , mudtStudentRecord
this statement write the whole contents of the variable mudtStudentRecord to the next
available record of the random access file #2, since the last Get or Put had moved the
file pointer. Notice the two consecutive commas in the middle of the statement.
- Use the Get command to obtain data (i.e. read) from a random access
file. You must store the data that you read into a userdefined data type. Examples:
- Get #1, intStudentRecord, mudtStudents
gets the next available record and stores it into intStudentRecords.
- Get #2, , mudtStudents
gets the next available record and stores it in the userfdefined data type.
- Sometimes it is necessary to determine the size of the user-defined data type that is
being used with a sequential access file. The LOF function can be used to determine the
length of a record as in:
intNumberRecords = LOF(1) / mudtStudentRecords
For i = 1 to intNumberRecords
etc.
Objective #9: Perform add, delete, and edit operations on random files.
Objective #10: Allow the user to input data using the InputBox function.
- The InputBox function can be more convenient to use to request inputted information from
a user than a text box. While the MsgBox function is used to simply display a message to
the user, the InputBox function provides a prompt and requires the user to input a value.
- The general form of the InputBox function is:
VariableName = InputBox("Prompt" [,
"Title"] [, Default] [, XPos] [, YPos])
- The Prompt is required and can be a string literal or a string expression. The Title
is the string that appears in the title bar of the input box. The Default is the default
value that the programmer wishes to appear in the input area of the input box. XPos and
YPos mark the left and top edges of the input box. If the prompt is long, you may use the
VB constant vbCrLf to make it appear on multiple lines.
CIS 230 Home Page | Mr. Minich's Education Home Page | Minich.com Web Design