ISM 3230 Introduction to Programming
Chapter 10: Data Files
Chapter
10 Student Learning OBJECTIVES: |
Upon
completion of this chapter, you will be able to:
- Create
data files.
- Read and
write records to disk.
- Determine
the appropriate locations for data-file related code.
- Explain
the purpose of a Close statement.
- Differentiate
between sequential and random files.
- Trap user
errors and handle errors to avoid run-time errors.
- Incorporate
fixed-length strings into user-defined data types.
- Read and
write objects in a random file.
- Perform
add, delete, and edit operations on random files.
- Allow the
user to input data using the InputBox function.
|
Data Organization Hierarchy:
Name |
Composition |
Example |
Bit |
0 or 1 |
10110 ... |
Byte / Character |
8 bits |
"C" |
Field |
Meaningful set of characters |
Name ("Jane Doe") |
Record |
Meaningful set of fields |
One student (name, SSN, GPA, etc.) |
File |
List of records |
Students.dat |
Database (DB) |
Set of integrated (linked) files |
Registration DB: students, classes, transcripts, ... |

Data Files
- Data files consist of records and fields
- Record key determines a record’s position in a file
- Two common file organizations are sequential and random
- Process a file by
1. opening the file
2. processing the data
3. closing the file
Opening Files
- When you open a sequential file, the first few records are read automatically
and placed in memory to speed processing.
- These records are stored in a buffer for later processing.
- The goal is to always have records available in high speed memory rather
than having to read, in real time, from relatively slow I/O devices.
Open statement’s form:
- Open "filename" For {Input|Output|Append|Random} as #Filenumber
[Len= No.]
Examples:
Open "A:\DataFile.Dat" For Input As #1
Open stFileName For Input As #intFileNumber
- Four File Modes:
- Output Writes at front of file, overwriting any extant
data
- Input Reads data from disk
- Append Writes new data at end of file
- Random Read/Write data to specific location & in any order
Close statement form: Close [#filenumber]
- Close #1 or Close
#1, #2
- Close issued automatically when you end
- Issue Close statement before leaving prog.
- Close empties the output buffer, writes an EOF (end-of-file) mark, releases
buffer, and releases the file number (so it can be reused, if necessary)
FreeFile Statements
- FreeFile function returns the next unused file number
- intFileNumber = FreeFile
- In large projects, file numbers are hard to track and allocate
Locating a File Number
- To locate an available file number for a large project, always use
the FreeFile function to locate an unused file number.
- You don’t care what number is chosen—only that it is available.
- Store the retrieved file number in a module or global variable so other
forms can manipulate the files, if necessary.
Obtain an available file number this way:
Dim intFileNum As Integer
intFileNum = FreeFile ‘Obtain
next available file number
Open "File.dat"
For Output As #intFileNum
- Whenever you reference the preceding file, you do so with the intFileNum
variable rather than a literal (number).
Sequential File Organization
- Sequential file records are stored one after another
- Use Write to output data
- Use Input to read data
- File must be opened prior to first use
- Form:
Write #fn, item1,
item2,…, itemn
Input #fn, item1,
item2,…, itemn
- EOF function signals end of file
Reading a Sequential File
- Form: Input #fn, item1,…,itemn
- Separate fields items with commas
- Input statement reads sequential data
Input #1, lblName.Caption, lblStreet.Caption
Example: reading sequential data file and populating two list boxes:
Do Until EOF(intFileNum)
Input #intFileNum, stName, stPhone
lstName.AddItem stName ‘add
name to a list box
lstPhone.AddItem stPhone ‘add
phone to a list box
Loop
Close #intFileNum ‘close
the input file
End of File (EOF)
- When reading a sequential file, the EOF condition is raised when you attempt
to read the n+1st record (n records total).
- The EOF function is used to determine when EOF occurs
- EOF form: EOF(filenumber)
- EOF returns false until end of file is reached.
- Typical read loop:
Do Until EOF(1)
Input #1, strCofFlavor, strRoastName, strRoastCity
Loop
- If the file contains five records, then EOF is raised on the fifth
input execution, not on the sixth Input.
Writing to a Sequential File
- Write statement places data in output
- Form: Write #file, o1,
o2, …, on
- You can separate fields with commas or semicolons
- Output fields are separated with commas, and strings are quoted.
- <Cr>/<Lf> ends each record
Write #1, txtLname.Text, 54.89
- Output fields are placed one after another and end with <CR>
- If you create a form to add records to a file, the Open statement
is commonly placed in the form Load event procedure
- Whereas, the write statement is placed in the click procedure of
an Add button.
Trapping Program Errors
- Errors may be trapped asynchronously
- Visual Basic generates an error number whenever an error occurs
- To handle errors, you must
- Turn on error handling feature: On Error...
- Create error handling code
- Determine what is to be done after processing the error (continue, end program,…)
Examples of Handling Errors
- Place On Error in any procedure that is
to traps and processes errors
- Example:
Private Sub Form_Load()
On Error GoTo HandleErrors 'Turn on error trapping
Open "A:\Testdata.dat" For Input As #1
… (more code here)
Exit Sub 'exit to avoid executing error routine
HandleErrors:
‘some
code to handle error
Resume
End Sub
- A line label is a name followed by a colon on a line by itself
- HandleErrors is a line label
- Forms of On Error statement:
- On Error GoTo linelabel transfer
control to label in module
- On Error Resume Next skip error line
& continue with next
- On Error GoTo 0 turns off error handling
The Err Object
- The Err object holds information about error that just occurred
- Err.Source holds the source of the error
- Err.Number holds the error number
- Err.Description contains error description
- You can raise an error condition—turn on an error—with:
Err.Raise Number:=xx
Error Numbers
Coding Error-Handling Routines
- On Error statement designates error handler
- Code to handle errors follows line label
- Line label appears on line by itself and ends with a colon
- A Case statement works well to sort out errors with a "switchboard"
- Continue execution with Resume statement
Using Case to handle errors
- Using Case to handle errors with a "Switchboard":
Select Case Err.Number
Case 53 'Handle error # 53 here
…
Case 71 'Handle error # 71 here
...
Case Else 'Handle all other errors here
…
End Select
Resume statement forms:
- Resume continues with line causing error (careful!)
- Resume Next continues with line following one that caused error
- Resume linelabel continues at line label, which must be in same
proc
Exit and Exit Sub Statements
- Exit statement jumps out of structure--a function, subroutine, or
loop
- Exit should be placed before line label of error handling routine so
normal program flow doesn't drop through the error code.
- Exit Sub immediately exits current sub procedure
- Exit Function immediately exits current function
- Exit is used to prematurely halt execution of sub procedure or function
when extraordinary conditions occur
- Place Exit Sub above error handling label
Saving Changes to a File
- When data changes, ask users if they want to save the changes before program ends
- Changed data is known as "dirty" data
- Keep track of data changes with a global boolean flag
- Any procedure that allows data to change should set the flag to True—indicating "dirty" data file
- Check file just before ending program
Unload and End
- You should Unload all forms before executing an End statement.
- This triggers each form’s Unload event (and each Class’s Terminate event),
giving you control at that point to check for "dirty" data files.
QueryUnload
- The best way to ask the user if they want to save changes is in the QueryUnload
event procedure.
- The QueryUnload event procedure obtains control when the (what else!) QueryUnload
event occurs.
- QueryUnload occurs when the user:
- clicks an Exit button or menu command to exit
- clicks on a window’s Close button
- or exits Windows altogether
QueryUnload procedure example:
Private Sub Form_QueryUnload(Candel As Integer,
UnloadMode As Integer)
Dim intResponse As Integer
If mblnIsDirty Then
IntResponse = MsgBox("Data
has changed. Save it?", _
vbYesNo + vbQuestion,
"Coffee List Changed Warning")
If intResponse = vbYes Then
mnuFileSave_Click
End If
End If
End Sub
Sequential File Prog. Example
- You can load a combo box by reading from a data file and executing the AddItem method
- Reading file & list filling halts when EOF occurs on input file
- (See Hands On Programming example)
Random data files
- You can read/write data in any order
- Open "filename" For Random As #1 LEN=x
- Get #filenumber, [record#], RecordName
- RecordName is a user-defined data type:
Type FullName
strLastName As String * 20
strFirstName As String * 15
End Type
Put #filenumber, [recordnumber],
Recordname
LOF - length of file
- LOF function used to locate end of file for a random file
LOF(filenumber)
- To find out how many records a file has, divide the file length by the record
length
InputBox
- An alternative to a textbox to get input from user
- InputBox is a function that prompts the user for data and then returns the
value
- Similar to MsgBox, but returns data which can then be assigned to a variable
Form:
VariableName = InputBox("Prompt",
[... optional parameters] )
strName = InputBox("Enter your
name.")
Chapter Summary:
OBJECTS
|
|
PROPERTIES
|
|
METHODS
|
|
STATEMENTS
|
|
FUNCTIONS
|
Err
|
|
Err.Number
|
|
Raise
|
|
Close
|
|
EOF
|
|
|
Locked
|
|
|
|
Exit Sub
|
|
FreeFile
|
|
|
Number
|
|
|
|
Exit Function
|
|
InputBox
|
|
|
Source
|
|
|
|
Get
|
|
LOF
|
|
|
|
|
|
|
Input
|
|
LTrim
|
|
|
|
|
|
|
On Error
|
|
RTrim
|
|
|
|
|
|
|
Open
|
|
Seek
|
|
|
|
|
|
|
Put
|
|
Trim
|
|
|
|
|
|
|
Resume
|
|
|
|
|
|
|
|
|
Write
|
|
|