Wyo VB - Ch. 9 Notes
Objective #1: Understand the 3 different kinds of
external data files that can be used by a VB project.
- 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. External 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. There are three
kinds of files that can be used with Visual Basic: random, sequential,
and binary. We will not study binary files in this course.
- sequential access files
- data is stored as a continuous stream of information
- to read one part of the data, you must pass through (that is, read)
all of the data that comes before the data that you are looking for
- sequential access files are like cassette tapes, you can only listen
to one song if you first listen to all of the songs that appear before
it
- word processor programs such as MS Word store data as sequential
access files. Most spreadsheet programs like MS Excel also store data
as sequential access files surprisingly.
- sequential access 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.
- The advantages of sequential access files are that they only use
the space required by the actual number of bytes present in the file.
- random access files
- data is organized in records, where a record is a complete
set of data. In many database programs, records appear as horizontal
rows. Vertical columns are called fields in a database program.
- within the structure of a record, any number of fields can be used
to separate different data types.
- all records are the same size (as far as bytes of memory go)
- random access files are like compact discs, you can immediately
jump to a specific record (or song). Any piece of data in a random
access file 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.
- database programs such as MS Access store data as random access
files
- 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.
- binary files
- all information is stored as individual bytes.
- Paint programs such as MS Paint store graphics files in a binary
format
- Files that have been opened within a program should be closed with a Close
statement before the program finishes executing. If this is not done,
you risk corrupting or damaging those external files. To close a file simply
use a statement like, Close
#1 where #1 is the file number associated with
the file that you want to close. If you want to close all external files that
you have open the statement, Close
, closes ALL open files.
- The Kill statement is very powerful. It actually deletes a file whose
pathname is specified! It is convenient to be able to delete files from within
a Visual Basic program but should only be done with extreme care. This not
only closes a file for use within a Visual Basic program but it permanently
deletes the file from the hard drive of your computer. Example:
Kill "C:\Temp\phone.txt"
would permanently erase the file phone.txt that is located in the Temp folder
of the computer's hard drive.
Objective #2: Create external sequential access data files.
- To create a sequential access data file, you can use any text-editing (e.g.
NotePad) or word-processing application (e.g. MS Word). If you are using a
program like Word, be sure to save the file as Text rather than in the native
Word format. The program NotePad is found under Start/Accessories on most
Windows PC's.
- Type each record (i.e. piece of data) onto a separate line or with commas
in between each record. Save the file with a .txt or
.dat extension so that other applications and people will recognize
the file as a data text file.
- You can create a sequential access data file from within a VB application,
as well. Using the Open statement (see below) 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.
Objective #3: Use data files with VB programs.
- Files must be opened by Visual Basic before they are used by the program
in any way. An example of an Open statement might look like this,
Open "Z:\MyFile.txt"
For Random Access Write
As #1 Len = 55
The location specified in quotes is the pathname
for the file that you would like to open. Be sure to type
the path correctly. If your operating system cannot find a file at the precise
location with the precise spelling that you've included here, your program
may crash. In the Wyo computer lab, your personal network files are located
on the Z: drive, not the C: drive.
After the keyword For, you must specify the mode
of file access. That is, Visual Basic must know how you wish
to use the file. You can work with the file in of 3 modes: Binary Access,
Random Access, or Sequential Access. For the first two modes,
you type either "Binary Access" or "Random Access" after
the keyword For. If you wish to use the file in the third mode, sequential,
you must type either "Input", "Output", or "Append"
after the keyword For.
If you choose Random Access or Binary Access modes, then you must further
specify what type of access you wish to use. Your
options are to type "Read", "Write", or
"Read Write". If you open a file with Read access, your program
can only open and input information from the file but not make any changes
to the data there. If you open a file with Write access, your program can
permanently change any data in that file but you cannot actually read or input
information from the file. If you choose Read Write access, your program can
read or input information from the file as well as to modify and write to
the file. If you are working in the Sequential Access mode, your use of the
words Input, Output, and Append will determine the type
of access. Input specifies Read access, Output specifies Write access and
Append specifies Write access. There is no equivalent of Read Write access
when working in Sequential Access mode. Therefore, a sequential access file
can either be opened for reading or writing but not both. You can however,
close a sequential access file that was opened for input (reading) and then
reopen it for output (writing).
You must specify the file number
(sometimes called channel number) that you wish to attach to that specific
file while your program executes. This can be any integer but it is customary
to open your first file as #1 and then to use #2, #3, etc. only if you need
to open several files from within the same program.
Only if you open a file in Random Access mode will you have to specify the
length of each record. A primary characteristic of random access files is
that they organize data into records of equal length. You must specify the
number of characters that are stored in each record of your random access
file by typing Len = X at the end of the Open statement where X is the length
(in characters) of each record.
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 labeled #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.)
- 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 #4: Read data from a sequential access file and write data
to a sequential access file.
- 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. As more Input statements are
executed the file pointer moves through the records or lines of a sequential
access file one by one in a forward only direction. 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. You cannot move
a file pointer backwards when working with a sequential access file. However,
closing a sequential access file (explained later) and re-opening it will
reset the file pointer to the beginning of the 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.) If the file was opened for output,
its file pointer starts 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. Writing to a sequential
access file that was opened in the Output type of access will overwrite the
contents of the file. Only if this kind of file is opened with the Append
type of access will the existing data be preserved. 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.
- 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
lstSample.AddItem strNext
Loop
where lstSample is a listbox that is used to store the string values found
in the data file. 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.
- Anytime that you close and reopen a sequential access file, its file pointer
resets to the beginning and points to the first character.
Objective #5: Use the Close statement to close files.
- 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 or corrupt a file to a point
where it can no longer be opened.
Objective #6: Use user-defined types to store data.
- You need to create a user-defined type of data for the Phone List
program. Besides using familiar variable data types such as integer, single,
string, etc., a programmer can create his/her own customized data type. You
can even give your new data type a name that you make up. You could create
a user-defined data type called Person
which actually stores three pieces of information (variables) together as
a record. Often user-defined types are used to store data within a random
access file. To create a user-defined type you must use the keyword Type.
You can only create user-defined types within the general declarations section
of the standard code module of a project. Therefore the variables created
with your user-defined type are global in scope and can be used anywhere in
your project. Example:
Type Person
Last As String
* 20
First As
String * 20
Phone As
String * 15
End Type
In the example, the name of the user-defined type is Person. The variables Last,
First, and Phone
are each string variables which go together to form records of type Person.
The size (in characters) of each variable is specified after the asterisk
(*). You should use indentation to show how the member variables are part
of the overall type, Person. you should capitalize the
first letter of the name of a user-defined type.
In your program you must declare a specific variable as type Person
with a statement like, Dim
Father As Person . This creates a variable called Father
which has three fields (called member variables), Last, First, and Phone.
In order to assign a specific last name to the Last field of Father, you need
to use the dot operator ( . ) like this,
Father.Last = "Smith"
.
You could even create an array of Person type with a statement like
Dim Students(1 To 10) As Person
.
Then this statement
Students(3).Phone = "374-4031"
would assign the string, 374-4031, to the Phone field of the 3rd element in
the array Students.
Objective #7: Use random access files along with user-defined types.
- The Put statement writes data to random or binary files. Example:
Put #1, 5, "John Doe"
You must specify the file number of the file to which you
wish to write some data.
In the example above, "John Doe" would be placed into record 5 of
the random access file. (If the file was opened in Binary Access mode, the
string "John Doe" would be placed into a position beginning at the
fifth byte of the file.)
- You can omit the middle number in a Put statement. Example:
Put #1, ,"John Doe"
Notice that two commas appear consecutively in the middle of the statement.
In this case, the data "John Doe" would be placed into the current
record of the file. Note that anytime a file is opened in any mode, Visual
Basic keeps track of the current position of the file with a file pointer.
- The Get statement reads a piece of data from a random or binary access
file. It works similarly to a Put statement. Example:
Get #1, 6, strName
Again, #1 is the file number from which you wish
to read some data.
In the example above, the statement reads record 6 of the file and then stores
that in the variable strName, which you can use later in your program.
Objective #8: Use the App.Path property of a VB project to make the
project portable
- When a VB project makes use of external data files, audio files, or any
other type of external file, it is important to make sure that the file is
always properly opened by the VB project even if the project's folder has
been moved to another location on the hard drive. A computer program is considered
to portable if it still executes properly when it is moved
to different locations on a computer or even to different computers.
- A VB project has a predefined App object which has a Path
property. You cannot change the Path property with an assignment statement
such as App.Path = "C:\Temp". Rather, you use the Path property
in file Open statements to be sure that your external data file opens even
if the project's folder has been moved to a different location on the hard
drive. For example, using the Open statement
Open App.Path & "\data.txt" For Input As #1
ensures that the file data.txt is properly opened no matter where the project's
folder has been placed. Notice the use of the concatenation operator ( &
) between the App.Path property and the string literal "\data.txt".
Of course, you should have the external data file, data.txt, stored in the
folder that contains your .vbp and .frm files (or in the same folder as your
.exe file if you have turned your program into an executable file.)
The App.Path property could also be used with the LoadPicture command in order
to change the picture that is displayed in a PictureBox. For example,
pctPlayerATank.Picture = LoadPicture(App.Path & "\destroyedTank.bmp")
Objective #9: Use the Make menu command to make an executable version
of a VB project
- Use the File/Make menu command to turn a VB project into a single executable
file. This will not affect your actual project. The new executable file will
have the extension .exe and can be run from the Windows XP desktop. With prior
Windows operating systems, a certain .DLL file needs to be placed into your
computer's Windows folders. That .DLL file may be freely available on the
Internet. Unfortunately, the executable file will not work on computers with
other operating systems such as Macintosh, Linux, etc.
- If your project uses external data files (random access or sequential access)
it will be necessary to distribute those files with your executable file as
well. In some cases, it is also necessary to distribute any audio, video,
animation, and graphic files that your program uses as well. The App.Path
property of the VB project needs to be used to make sure that the executable
version of the project can still access the external files. It would be wise
to create a folder that contains your .exe file as well as the other files
and perhaps keep the other files in subfolders within the main folder. Notice
that commercial applications such as Word and games that you've installed
on your home PC consist of many files (an .exe file and many external data
files) that are always located in a single application folder.
Objective #10: Use selected API function calls including those that
allow audio clips to play
- API stands for "Application Programming Interface". By including
a reference to an API function that has already been included with your computer's
Windows operating system, you can call a function that someone else wrote
within your VB program. Even if an API function was written in another programming
language such as C++, you can still call it from a Visual Basic program! There
are many Windows API's that you can make use of in this way.
- One API function that you may wish to use is mciSendString. By including
this code at the top of a form,
Private Declare Function mciSendString Lib "winmm.dll" Alias
"mciSendStringA" _
(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength
As Long, ByVal hwndCallback As Long) As Long
you can call the function mciSendString from within your program. Here is
a complete sample of how you can play a .wav audio file with mciSendString,
Private Sub Command1_Click()
' play a .wav audio file
Dim intError As Long
' error value returned by mciSendString
API function
Dim strFileName As String
'
name of the audio .wav file
Call mciSendString("stop sound", 0, 0, 0)
' in case the sound was already playing
Call mciSendString("close sound", 0, 0, 0)
strFileName = "boing.wav"
' assuming the audio
file is in the folder with the VB project
' To be safe try to open the sound file first,
' if there is an error then do not try to play the sound
file
' intError will be zero if no error occurred
intError = mciSendString("open waveaudio!"
& strFileName & " alias sound", 0, 0, 0)
If (intError <> 0) Then
MsgBox "Error! Probably file not
found. Modify the code to point to a .WAV file on your system."
Else
Call mciSendString("play sound",
0, 0, 0)
End If
End Sub
Here is an example of how to play a .mid (MIDI) audio file:
Private Sub Command2_Click() ' PLAY MIDI FILE
Dim i As Long
Dim RS As String
Dim cb As Long
Dim W As String
RS = Space(128)
W = "star_spangled_banner.mid"
i = mciSendString("stop midi", RS, 128, cb)
i = mciSendString("close midi", RS, 128,
cb)
' make sure
no midi files are open or playing
i = mciSendString("open sequencer!" &
W & " alias midi", RS, 128, cb)
If (i) Then
MsgBox "Error! Probably file not
found. Modify the code to record and play a .MID file on your system."
Else
i = mciSendString("play midi",
RS, 128, cb)
End If
End Sub
- Another Windows API that can be used to play sound is sndPlaySound. Add
the following code to your standard code module:
Public Declare Function sndPlaySound Lib "winmm.dll" Alias
"sndPlaySoundA" _
(ByVal lpszSoundName As String, ByVal uFlags As Long)
As Long
Public Const SND_ALIAS = &H10000
Public Const SND_ASYNC = &H1
Public Const SND_LOOP = &H8
Public Const SND_NOWAIT = &H2000
and then use the line of code
sndPlaySound("boing.wav", SND_ASYNC)
to play the sound.
- See this
tutorial for more information on using other API function calls with VB.
Objective #11: Use selected third party controls (.ocx) including the
VB Multimedia 6 control.
- There are a number of customized controls that you can add to your VB Toolbox.
Click the Project/Components menu command to see a list. By placing a checkmark
next to an entry and clicking "Apply", you will see a new icon in
your Toolbox.
- Another way to play sound is to add the "Microsoft Multimedia Control
6.0" component to your project and then add a multimedia control object
to a form. See http://www.freevbcode.com/ShowCode.Asp?ID=1547
for further instructions.