Académique Documents
Professionnel Documents
Culture Documents
Update Edition
Chapter 10 Data Files
Data Files
Files stored on disk device Contain actual data Records ==> Rows or lines Fields ==> Data elements within row Usually stored in an organized manner
Sorted by one of the fields Key Field, unique data item for each record
Records end with CR, File ends with EOF Fields separated by comma delimiters
Variable length Strings enclosed in quotes Numbers not enclosed in quotes
"Lynne","Weldon","999 Wide Way","Aiken","SC","29803" <CR> "Jim","Buck","1 Cow Lane","Aiken","SC","29801" <CR> "Tom","Thumb","PO Box 200","Aiken","SC","29802-200" <EOF>
Records are fixed length and have a record number for reference Fields are fixed length and position
Less data then length will be padded with spaces More data than length will be truncated
Read or written in any order Think of the structure being "like a table"
Open Statement
Open "fully qualified path for filename" For {Input| Output|Append|Random} As #FileNumber [Len=RecLength] { } indicates required - pick one [ ] indicates optional FileNumber = 1 to 511, RecLength Max = 32,767
Tip: Instead of specifying entire path, always store the sequential files in the same directory as your VB Project and use App.Path to specify the path
2002 The McGraw-Hill Companies, Inc. All rights reserved.
Open For
Input
reads a previously stored file from disk
Output
writes file to disk beginning at BOF, overwriting previous records
Append
Writes file to disk beginning at existing EOF
Random
Reads or writes random files
10
Sequential
Open "C:\VB6\myfile.txt " For Input As #6 Open "A:\myfile.txt " For Output As #1 Open App.Path & \myfile.txt " For Append As #2
Random
Open "A:\myfile.txt " For Random As #3 Len=60
11
12
Locating a File
Problem: Open statement requires fully qualified path for filename Alternative 1:
Require that all data files be saved in the same directory as the VB project Use App.Path to specify the path as follows, Dim strPath as String strPath=App.Path & "\Filename.extension" Open strPath for Input as #4
Alternative 2:
Use Common Dialog with ShowOpen method to display Open dialog for user to locate file
13
Locating a File-Using Common Dialog Dim strFileName as String With dlgCommon .DialogTitle = "Open" .CancelError = False .Filter = "All Files (*.*)|*.*" .ShowOpen If Len(.FileName) = 0 Then Exit Sub End If strFileName=.FileName End With Open strFileName for Input as #1
14
Close Statement
Terminates processing of a disk file Usually coded in Form_Unload, mnuFileSave, mnuFileSaveAs, mnuFileExit
Close [#FileNumber]
[] indicates optional If FileNumber is omitted then all open files are closed
2002 The McGraw-Hill Companies, Inc. All rights reserved.
15
16
Physically writes the last partially filled buffer to disk for sequential files (Write statement has placed data in the buffer) Writes EOF Releases the Buffer Releases the FileNumber
Note: END closes all open files but is not the best way to close files. You should close files explicitly!
17
Update Edition
Sequential Files
19
Open an existing file for Input Use Input Statement to read the records
20
Input Statement
Usually coded in Form_Load If populating a listbox or combo use a Do Until EOF to read data
21
Dim strVideoTitle as String Do Until EOF(3) Input #3, strVideoTitle cboVideoTitle.AddItem strVideoTitle Loop Noticenumbersmatch!
2002 The McGraw-Hill Companies, Inc. All rights reserved.
22
Write Statement
Use to place/save data in a sequential file File must already be opened "For Output" Place code in mnuFileSave, mnuFileClose or Form_QueryUnload Follow with a Close statement
23
Example
Write #FileNumber, List of variable or fields Write #1, txtFirstName, txtLastName, txtStreet, txtCity, txtxState, txtPhone Write #2, strCourseNum, strClass, intHours
24
Dim intIndex as Integer Open "A:\videos.txt" For Output As #1 For intIndex=0 to cboVideoTitle.ListCount-1 Write #1, cboVideoTitle.ListIndex Next intIndex Close #1
25
26
Name "old fully qualified path for filename" As "new fully qualified path for filename" Name "A:\Names.txt" As "A:\People.txt"
27
28
Open the file for Append Allow the user to enter new data using textboxes or other controls on a form Write the data once a complete record of data has been entered Close the file after all new records have been inserted
29
Open the file for Output If the filename does not exist VB will create the file Write data to the file from textboxes or other controls the user enters data into Close the file
30
Standard practice is to ask the user if they want to save the changes before program termination
Set up a module level Boolean variable to identify if changes have been made In Form_QueryUnload event
Check module level Boolean variable to see if changes have been made If TRUE ask the user if they want to save If user responds "yes", save
Update Edition
Trapping Program Errors
32
Error Handling
Trap run-time errors rather than having user deal with them or program terminating Some problems cannot be avoided - BUT they must be anticipated
Drive or printer not functioning Improperly formatted disk File not found
33
11 13 482 53 61 68 71 75 76
Division by 0 Type mismatch *** Printer error File not found Disk full Device unavailable Disk not ready Path/file access error Path not found
34
VB generates an error number VB checks the number against a table of known error codes Programmer can intercept the error code and take action before VB terminates the project
35
Turn on the error-handling feature using On Error statement in subprocedure Create error handling code routines
Set them off from other code with line labels
36
On Error Statement
Use this statement at the beginning of a procedure to activate error trapping Designate a line label in the same procedure to go to if an error occurs
Line labels - begin in column 1, end with colon:
37
Precede with Exit Sub statement (or Exit Function) Check the error number(s)
Single error number -- If structure Multiple error numbers -- Select Case
38
Resume
What line of code should be executed after the error has been handled? Resume - line of code that caused error Resume Next - line of code that would logically be executed after the line of code that caused error Resume line label - line with indicated label
39
Err Object
Intrinsic VB object (like Printer object you used in 1st semester VB class) Properties
Number - error number, 0 to 65,535 Source - object or application that caused error Description
Method
Raise - set an error number and/or cause it to occur
40
Use Resume if you identify the problem and the user could correct it Use Resume Next if you identify the problem and execution can proceed without running the error generating line of code Raise the error again (Err.Raise Err) if you cannot identify the problem so VB will handle it and generate a system error message
41
Use Resume line label if you want to exit the procedure Call you exit procedure (perhaps, mnuFileExit) to end without displaying any error message Turn off error handling/trapping with: On Error GoTo 0
42
Handling One Error Number Private Sub Whatever( ) On Error GoTo ErrorHandler code to do whatever this subprocedure does Exit Sub ErrorHandler: If Err.Number=71 msgbox to inform user of error for correction Resume Else Err.Raise Err End If End Sub
2002 The McGraw-Hill Companies, Inc. All rights reserved.
43
Handling Multiple Error Numbers Private Sub Whatever( ) On Error GoTo ErrorHandler code to do whatever this subprocedure does Exit Sub ErrorHandler: Select Case Err.Number Case 71 Msgbox Case 53, 76 Msgbox Case Else Err.Raise Err End Select Resume End Sub
2002 The McGraw-Hill Companies, Inc. All rights reserved.
Update Edition
Random Files
45
Records are fixed length and have a record number (data type=long integer) for reference Fields are fixed length and position
Less data then length will be padded with spaces More data than length will be truncated
Read or written in any order Think of the structure being "like a table"
46
47
Must be done before reading or writing Use Type/End Type statements Code in General Declarations Use fixed length strings
Specify length in Dim statement Ex: Dim strFName as String * 20
48
Type/End Type
PrivateTypePerson intEmpNum AsInteger strFName AsString*20 strLName AsString*30 strPhone AsString*12 curRate AsCurrency EndType DimmudtPersonRecordAsPerson OpenApp.Path&"\Names.dat"ForRandomas#1 Len=Len(mudtPersonRecord)
Note:mudtprefixforUserDefinedType
2002 The McGraw-Hill Companies, Inc. All rights reserved.
49
Open Statement
Once the random file is opened it can be used for both input and output unlike sequential files! If you open a file that does not exist, VB will create it as an empty file Once opened, data are available for read/write operations one record at a time
50
Open an existing file for Random Use Get Statement to read the records
51
Get Statement
Usually coded in Form_Load If populating a listbox or combo use a Do Until reach last record to read data
Get #FileNumber, [RecordNumber], RecordName Get #2, 4, mudtPersonRecord Get #2, intRecordNumber, mudtPersonRecord
[]indicatesoptional,ifRecordNumberisomitted,thenextrecordisread
2002 The McGraw-Hill Companies, Inc. All rights reserved.
52
Put Statement
Use to place/save data in a random file File must already be opened "For Random" Place code in mnuFileSave, mnuFileClose or Form_QueryUnload Follow with a Close statement
53
Put #FileNumber, [RecordNumber], RecordName Put #2, 4, mudtPersonRecord Put #2, intRecordNumber, mudtPersonRecord
[]indicatesoptional,ifRecordNumberisomitted,thenext recordisread
2002 The McGraw-Hill Companies, Inc. All rights reserved.
54
Get and Put operate on an entire record Reference the individual fields using dot notation for the User Defined Type
55
56
LOF Function
Length of File function returns the size of the file in bytes Use instead of EOF used for sequential files To determine the highest record number in the file divide LOF by the size of one record
57
Seek Function
Returns the current location of the pointer = the next record in the file to be processed
Seek(FileNumber) intNextRecord=Seek(3)
58
Trim Functions
Remove extra blank spaces in a string Trim ==> removes spaces from both ends LTrim==> removes spaces at left end RTrim ==> removes spaces at right end
59
Sub GetRecord(lngRecNum as Long) Get #1, lngRecNum, mudtPersonRecord With mudtPhoneRecord txtEmpNum.Text = .intEmpNum txtFName.Text = RTrim(.strFName) txtLName.Text = Rtrim(.strLName) txtPhone.Text = Rtrim(.strPhone) txtRate.Text = .curRate End With End Sub
60
Sub PutRecord(lngRecNum as Long) With mudtPhoneRecord .intEmpNum=Val(txtEmpNum.Text) .strFName = txtFName.Text .strLName = txtLName.Text .strPhone = txtPhone.Text .curRate = Val(txtRate.Text) End With Put #1, lngRecNum, mudtPersonRecord End Sub
61
When you Get or Put a record you need to know the record number To keep track of record numbers store them in ItemData property of ListBox When user selects a value from the list, read its ItemData property to retrieve the desired record
62
Create routines to
Edit existing records Add new records Delete existing records
63
Display the record Disable all command buttons except Save and Cancel Lock text boxes for fields containing data you do not want the user to modify
64
Clear all text boxes on form Disable all command buttons except Save and Cancel When user clicks Save write the new record at the end of the file If using a list box to store record numbers, update listbox by adding new data and record number
65
Delete Existing Records No way to delete a record in place Various methods are used to indicate that a record is to be treated as "deleted"
Write a special character in an existing field to indicate deleted Include a "Delete Code" field in the record description and mark it True to indicate deleted
If using a list box to store record numbers, update listbox by deleting the record's associated data and record number
Update Edition
Programming Hints
67
InputBox Function
Used to request simple input from user Similar in syntax and usage to the MsgBox function Includes
prompt to inform user of desired input text box for user to enter input OK and Cancel command buttons
68
InputBox Syntax
69
InputBox Examples
strName = InputBox ("Enter Your Name") intQuan = InputBox ("How many do you want?", _ "Order Quantity", 1)