290 likes | 456 Views
Visual Basic Programming II Lecture 5. MIS233 Instructor – Larry Langellier. This Week – Storing Information in Files. Understand sequential file design concepts Write, read, and append to a sequential file Use built-in Visual Basic file-processing controls
E N D
Visual Basic Programming IILecture 5 MIS233 Instructor – Larry Langellier
This Week – Storing Information in Files • Understand sequential file design concepts • Write, read, and append to a sequential file • Use built-in Visual Basic file-processing controls • DriveListBox, DirectoryListBox, FileListBox • Common Dialog Control • App Object • Error-handling • Combined with file processing
File Processing • Programs typically create data and require data to operate • When a program ends, any data created or entered is lost • Files are used to “permanently” retain information so it can be loaded the next time an application is run • Accessing info stored in a file can be done in three ways: • Sequential • Data managed as one continuous stream of characters • Typically used for storing text and log files • Processing occurs line-by-line – in order • Random • Identically sized records are stored and accessed • The record is defined by a User Defined Type with every string declared of fixed length • Processing can “jump around” • Binary • Can hold any form of data - things like bitmaps, sound files and executables
File Records • All three access methods can deal with records • Consider a User-Defined Type Type Patient PatientID As String * 9 Name As String * 30 Ward As Integer End Type • Each element of the “record” type is called a field, thus PatientID is a field • A collection of all fields for one person represents a single record • A collection of all records (many people) represents a data file
Sequential File Access • Useful for text files where each character in the file represents text or formatting • Text processing is limited to reading and writing strings, not sets of records • Two files are typically required, one for reading and another for writing – you can not read and write the same sequential file at the same time • If you want to insert a new line in a sequential file you must read from one file and write to a second until you reach the insert point – insert the new text in the second file and proceed reading/writing the rest of the source file
The Open Statement • Before a file can be used it must be opened • You can create or open a file with the Open Statement • Syntax Open <file> For [mode] As [#] filenumber • Components of syntax • file – the filename to be opened • mode – Append, Binary, Input, Output, Random • If you open an existing file in Output mode, you will overwrite the old contents – use Append mode to add to the existing info • filenumber – An integer from 1 to 511 • The function FreeFile returns an available file number
Reading Data from a File • Be sure to Open the file in Input Mode first • Three ways to read: • Input • A function that reads a specified number of characters into a string • Often used to place an entire text file into a string • Syntax: strIn = Input (number, [#]filenumber) • Where number is the number of characters to be read • The LOF(filenum) function tells how many characters are in a file • Example: 18.6 • Line Input # • Reads a text file one line at a time, reading all characters until a CR or LF is reached • Syntax: Line Input #filenumber, variablename • The line of text is read into the 2nd parameter • The EOF(filenumber) function is used to detect when the end of the file has been reached • Example: 18.7
Reading Data from a File (cont.) • Ways to read from a file (cont.) • Input # • Reads a list of numeric or string expression • Assumes that… • Individual values are separated by commas • String values are enclosed in double-quotes • Used when the exact type of data is known • Syntax Input #filenumber, var1[, var2, ... , varN] • Where var1, var2, etc. are the names of variables that input values will be read into • Example: 18.8
Writing Text to a File • Open a file in Output or Append Mode first • Print # • Does not add comma delimiters • Typically used in tandem with the Line Input # statement or the Input function • Syntax: Print #filenumber, expression • Where expression is the String to be output to the file • Example: Revisit 18.6 • Write # • Separates each value with a comma and puts quotation marks around string expressions • Usually paired with the Input # statement • Typically used when writing a sequential record for a file • This format can be imported by other applications (I.e. Excel, etc.) • Syntax: Write #filenumber [, expressionlist] • Example: Revisit 18.8
You’re done with a file, now what… • The Close statement • When everything has been read or written, the file should be closed • Syntax: Close [[#]filenumber] [, [#]filenumber]… • With no arguments, all open files are closed • The Kill statement • Used to delete a file from a disk • Syntax: Killfilespec • Example: 18.9
Additional Functions for Sequential File Processing • Dir – return a file or directory matching a pattern • Syntax: Dir [pathname] • pathname can contain wild-cards * and ? • FileCopy – copy a file • Syntax: FileCopysource,destination • FileDateTime – string indicating when file was created • Syntax: FileDateTime (pathname) • FileLen – the size (in bytes) of a file (must be closed) • Syntax: FileLen (pathname) • GetAttr, SetAttr – attributes of a file – read-only, etc. • Syntax: GetAttr (pathname) SetAttrpathname, attributes • Loc – current position in an open file • Syntax: Loc (filenumber)
Do It Together! Write a program that reads in a series of Integers from a file named inData.dat, sorts them in descending order (with a BubbleSort), and then write the sorted result back out to a file named outData.dat.
Sample Solution Private Sub Command1_Click() Static Numbers() As Integer Dim fnum As Integer Dim count As Integer Dim strNumber As String Dim i As Integer count = 0 fnum = FreeFile Open "A:\inData.dat" For Input As #fnum Do While Not EOF(fnum) Line Input #fnum, strNumber count = count + 1 ReDim Preserve Numbers(count) As Integer Numbers(count) = Val(strNumber) lstOriginal.AddItem strNumber Loop Close fnum Call BubbleSort(Numbers) fnum = FreeFile Open "a:\outData.dat" For Output As #fnum For i = 1 To UBound(Numbers) lstSorted.AddItem Numbers(i) Print #fnum, Numbers(i) Next i Close fnum End Sub
Built-in File Processing Controls • VB provides three controls to deal with file processing • Drive ListBox control – display available disk drives • Directory ListBox control – display the directories created for a drive • File ListBox control – display the files stored within directories • Example 18.1
The Common Dialog Control • The CommonDialog control integrates the drive, directory and file ListBoxes into one control • The CommonDialog control doesn’t perform any actual actions, but it provides a dialog for users to communicate their selections prior to some common operations • The Common Dialog provides user support for numerous operations, such as: opening a file, saving a file, selecting a color, selecting a font, printing a file, or displaying the Help System • The CommonDialog is not normally available in your ToolBox – you have to add it like the MSFlexGrid
CommonDialog methods • This is actually a single control which can have many different looks – you determine which appears by use of different methods • ShowOpen: Open a file • ShowSave: Perform a “Save As” operation for a file • ShowColor: Change a color selection • ShowFont: Change a font selection • ShowPrinter: Display the Print or Print Option dialog • ShowHelp: Invoke Windows Help • Example: 18.2
CommonDialog properties • Key Properties for the CommonDialog control when you want to open or save files are: • Filter • FilterIndex • DialogTitle • Filename • Flags • The Filter Property • Specifies the types of files to be displayed in a file listbox • Syntax: CMDialog.Filter [= "desc1|filt1|desc2|filt2..."] • Example CMDialog.Filter = "All Files (*.*)|*.*|Text Files (*.txt)|*.txt"
The Common Dialog Control (cont.) • The FilterIndex Property • Specifies the default filter, the first one is 1 • Example CMDialog.FilterIndex = 2 ‘Display *.txt files • Example: Revisit 18.2 • The DialogTitle Property • Sets the title for the dialog box • The Filename Property • Used to select a particular file or return a selected filename • The Flags Property • Used to customize the appearance and behavior of the dialog • Example: 18.3
The App Object • The App Object is a global object available at runtime • Properties • Path - returns a String denoting the application’s current working drive and directory • EXEName – the name of the compiled executable • Major, Minor, Revision – the version numbers for the application • ChDir and ChDrive are often paired with App.Path • Examples ChDrive App.Path ChDir App.Path
Do It Together! Extend the prior “Just Do It!” exercise to utilize a CommonDialog control to determine what input file to open and also to name the output file.
Sample Solution Inside Command1_Click() With cmdFiles .DefaultExt = ".dat" .DialogTitle = "Open the Input File" .Filter = "Data Files (*.dat)|*.dat|All Files (*.*)|*.*" .ShowOpen End With Open cmdFiles.FileName For Input As #fnum 'Read, Put in ListBox, Sort, Put in other ListBox With cmdFiles .DialogTitle = "Save the Sorted Numbers" .ShowSave End With Open cmdFiles.FileName For Output As #fnum
File Processing Error-Handling • As you begin to develop larger programs (like your Projects) you should begin to add error-handling code to nearly every procedure • Let’s see what happens without error-handling • Example: 18.4 • The Err Object – automatically stores info about errors • Properties • Number – the number of the error raised • Description – a text description of the error • Source – a string specifying the object or application generating the error • Methods • Clear – clear all properties of the Err Object • Raise – manually generate a run-time error
The On Error Statement • You can code your procedures so that errors are handled when they occur • The On Error statement tells your procedure where to jump to when an error occurs • The On Error statement has three forms: • On Error Resume Next • Control transfers to the line following the error • On Error GoTo 0 • Turn off error trapping – ignore all errors • On Error GoTo <label> • When an error is raised, transfer control to a line number or label where error handling code can process it • A list of error numbers can be found in VB Help under the topic “Trappable Errors”
The Resume Statement • The Resume statement can be used in an error-handling routine to affect where the program will flow next • Three forms • Resume(0) • Resume execution with the statement that caused the error • Resume Next • Resume execution at the statement after where the error occurred • Resume <label> • Jump to the label and start executing from there • Example 18.5 • You don’t have to Resume, you could exit the procedure or the application from within your Handler
Do It Together! Enhance the prior two “Just Do It!” solutions with an Error-Handler. This error handler should allow the user to fix a situation where a file being requested isn’t currently available. This could be handled in different ways – you could pop up a MsgBox alerting them to insert the disk or you could pop up the CommonDialog to allow them to reselect.
Sample Solution Inside Command1_Click() On Error GoTo ErrHandler 'The rest of the code remains the same… Exit Sub ErrHandler: If Err.Number = 71 Then MsgBox "The file you selected is not available. Reselect." cmdFiles.ShowOpen Resume 0 End If End Sub
Details… • Tonight • Midterm Project Assignment Handout • Next Class • Read Chapter 16: Numeric Functions • Homework #6 will be due at the beginning of class