chapter 5 basics of file input and output reading, writing, and printing text files 5 exploring...
TRANSCRIPT
Chapter 5Basics of File
Input and Output
Reading, Writing, and Printing Text
Files
5
Exploring Microsoft Visual Basic 6.0Copyright © 1999 Prentice-Hall, Inc.By Carlotta Eaton
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 2
Objectives...
1. Use Common Dialog control2. Display dialog boxes to open and save
files, set printer options, and select colors and fonts
3. Implement file I/O operations such as open, close, save and print
4. Write code to open a file and display it, then save changes to the file
5. Text, binary, RTF and HTML file formats
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 3
Objectives
6. Sequential vs. Binary vs. Random file access
7. Use File System Object (FSO) model to process files
8. Use string functions9. Print form and text from your project10. Write code to handle errors and avoid
runtime error crashes
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 4
Windows Dialog Boxes
Open Dialog BoxSave As Dialog BoxPrint Dialog BoxColor Dialog BoxFont Dialog Box
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 5
Common Dialog Control
CommonDialogName.MethodWhere
CommonDialogName is the name property assigned to the common dialog control
Method is one of the following:
ShowOpen displays the Open dialog box
ShowSave displays the Save As dialog box
ShowColor displays the Color dialog box
ShowFont display the Font dialog box
ShowPrinter displays the Print dialog box
ShowHelp starts the Windows Help engine
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 6
Open Dialog Box
Common Dialog control ShowOpen method
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 7
Save As Dialog Box
Common Dialog control ShowSave method
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 8
Print Dialog Box
Common Dialog control ShowPrinter method
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 9
Color Dialog Box
Common Dialog control ShowColor method
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 10
Font Dialog Box
Common Dialog control ShowFont method
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 11
The Common Dialog Control
Common dialog control provides access to Windows’ most commonly used dialog boxes
First add the Common dialog ActiveX control to the toolbox
Filter property selects the files to display based on file
extensions Example:
“Text file (*.txt) | *.txt”
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 12
The Sticky Pad Project
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 13
Create the Sticky Pad Project using the Common Dialog
Control
Hands-On Exercise 1 Create and test a new form Add the common dialog control Create the menus Add code for menus Display the Open dialog box Display the Save As dialog box Add and test code for the Close Note menu Add Banner comments
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 14
Instances and Classes
Class formal definition of an object Analogy - gingerbread man cookie
cutter
Instance one of the set of objects that belongs to
a class Analogy - any of the gingerbread men
cookies
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 15
Types of Files
File - block of information stored on disk or another media
Text file - file that contains lines of written information that can be sent directly to the screen or printer
Binary file - file that contains bits that do not necessarily represent printable text Examples: Word file, machine language file
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 16
Types of Files
RTF file (Rich Text Format) - standard developed by Microsoft to format documents
HTML (Hypertext Markup Language) - used to define formatting for web page files
Note: Rich Text Box control is only available in the Professional and Enterprise editions
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 17
File Access Methods
I/O (Input/Output) - refers to an operation or program that enters or extracts data from a computer
Access - read data from or write data to a storage device
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 18
File Access
Sequential access - used to read and write text files in continuous blocks
Random access - used to read and write text or binary files structured as fixed-length records
Binary access - used to read and write files that are structured according to an application’s specifications
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 19
Reading and Writing Files
Statements and FunctionsOpen statementInput functionInput # statementClose statementLOF (Length of File) functionPrint # statement
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 20
The Open Statement
Open pathname For mode As #filenumberWhere
pathname is a string that specifies a filename, and may include the folder and drive
mode must be one of the following:
Append, Binary, Input, Output, or Random
filenumber is a valid file number from 1 to 511
Note: The FreeFile function is used to obtain the next available file number
Example:
Open Filename For Input As #1
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 21
The Close Statement
Close #filenumberWhere
filenumber is any valid file number. If the filenumber is omitted all active files are closed.
Example:
Close #1
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 22
The LOF Function
LOF(filenumber)
Where
Filenumber is a valid file number
Example:
FileLength = LOF(1)
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 23
The Input Function
Input(charnumber, filenumber) Where
Charnumber is the number of characters to read
Filenumber is any valid file number
Example:
String = Input(Number, 1)
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 24
The Print # Statement
Print #filenumber, outputname Where
filenumber is any valid file number
outputname is the object to be printed
Example:
Print #1, txtNote
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 25
Open, Read and Write a File
Sub FileIO()Dim Pathname as StringDim FileLength As longOpen Pathname For Input As #1FileLength = LOF(1)txtFile = Input(Filelength, 1)Close #1‘Do other stuff hereOpen Pathname For Output As #1Print #1, txtNoteClose #1
End Sub
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 26
The File System Object
FSO - new feature of Visual Basic 6.0 Provides and object based model for
working with drives, folders, and files FileSystemObject object - primary object Drive object - info about a drive such as space Folder object - create, change, move and
delete Files object - create, delete, change and move TextStream object - enables you to read and
write text file
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 27
The File System Object
Useful Functions and Methods CreateObject function OpenTextFile method TextStream object methods and
properties
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 28
FSO Example Code Sub OpenTextFile()
Const ForReading = 1Const ForWriting = 2Const ForAppending = 3Dim fso ‘File System ObjectDim textfile ‘textstream file
Set fso = CreateObject(“Scripting.FileSystemObject”)Set textfile = fso.OpenTextFile(“C;\testfile.txt”,_
ForWriting, True, TristateFalse)textfile.Write “This is a test.”textfile.Close
End Sub
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 29
Handling I/O Errors
Bug - mistake in a computer programCompiler errors - occur when the rules of
the Visual Basic programming language were not followed
Runtime errors - occur when executing a program
Logic errors - occur when the program makes a mistake in understanding the problem or implements solution incorrectly
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 30
Handing I/O Errors
On Error GoTo LineName must be the first executable
statement in a procedure If error is encountered, the program
will execute the code immediately after the LineName statement
Place an Exit Sub statement immediately before LineName statement
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 31
Handling I/O ErrorsSub FileIO()‘Purpose: Error handling example
Dim Pathname As String On Error GoTo ErrorHandler ‘set up handler‘Insert code to open, save, or print file here‘No errors encountered hereExit Sub
ErrorHandler:‘Display a message box and exit procedureMsgBox “Cannot complete file operation”Exit Sub
End Sub
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 32
Add File I/O to Sticky Pad Project
Hands-On Exercise 2 Open the Sticky Pad project Add code to open a text file Add code to save a text file Add code to display the font dialog box Test the font dialog box Add code to display the color dialog box
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 33
Working with Strings
Len (Length of String) function - finds the length of a string
InStr (In String) function - searches a string for a substring
Left function - finds the leftmost characters of a string
Right function - finds the rightmost characters of a string
Mid function - finds characters in the middle of a string
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 34
The Len Function
Len (string | varname) Where
String is any valid string expression
Varname is any valid variable name
Either string or a varname is given, not both
Example:
If Len(Filename) = 0 Then Exit Sub
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 35
The InStr Function
InStr(startposition, string, substring)Where
startposition sets the starting position for the search
string is the string you are searching
substring is the substring you are looking for
Example:
Position = InStr(Pathname, “\”)
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 36
The Left Function
Left(string, length)Where
string is any valid string expression
length indicates the number of characters to return
Example:
FirstEight = Left(string, 8)
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 37
The Right Function
Right(string, length)Where
string is any valid string expression
length indicates the number of characters to return
Example:
LastEight = Right(string, 8)
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 38
The Mid Function
Mid(string, startposition, length)
Where
string is any valid string expression
startposition sets the starting position for extracting the substring
length indicates the number of characters to return
Example:
MiddleWord = Mid(string, start, 6)
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 39
Working with Printers
We can print 3 different ways We create a form, then print the form Send text and graphics to the default
printer using the system defaults Display the Print dialog box to offer
printing options, set the printer options, then send to the user’s choice of printers and print
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 40
The PrintForm Function
FormName.Printform
Where
FormName is a form object. If this object is omitted, the selected form is printed.
Example:
frmMain.PrintForm
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 41
Working with Printers
Print Form is a quick and easy way to print
Prints at screen resolution 72 - 96 dots per inch
Printers are capable of resolutions of300, 600, 1200 or more dots per inch
So, print out is low quality
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 42
The Printers Collection
Set as the default printer
Another printer
A fax card
A file stored on disk
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 43
Working with the Printer Object
Printer Object device-independent drawing space
that supports text and graphics Send signal to start print job Place text or graphics on pages Print the page Start a new page and continue until
finished
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 44
The Printer Object
Printer.method Where
Printer is the default print
Method is one of the followingPrint Objectname
New Page
End Doc
KillDoc
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 45
Working with the Printer Object
Private Sub mnuPrint_Click()‘Purpose: Print note using system defaults
On Error GoTo PrintErrorPrinter.Print ; ‘initialize printerPrinter.Print Me.Caption ‘send to printerPrint.Print vbCrLf; ‘send linefeedPrint.Print Me.txtNote ‘send textboxPrinter.EndDoc ‘print and endExit Sub
PrintError:MsgBox “Can’t print sticky note file “& Pathname
End Sub
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 46
Set Printer Object Properties
Printer.property Where
Printer is the default print
Property is one of the following
FontName, FontSize
FontBold, FontItalic
ScaleLeft
ScaleTopPage
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 47
Display the Print Dialog Box
Print Setup Print
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 48
Display the Print Dialog Box
Print #filenumber, outputname Where
filenumber is any valid file number
outputname is the object to be printed
Example:
Print #1, txtNote
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 49
Set the Flags Property
CommonDialogName.Flags FlagConstant Where
CommonDialogName is the name property assigned to the common dialog control
Flags is the method
FlagConstant is one or more of the following
cdlPDPrintSetup ‘display print setup
cdlPDHelpButton ‘display help button
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 50
Set More Properties for Printing
CommonDialogName. MethodWhere
CommonDialogName is the name property assigned to the common dialog control
Method is one of the following
Copies ‘number of copies to print
FromPage ‘page to start printing
ToPage ‘page to stop printing
hDC ‘selected printer
PrinterDefault = Setting
‘if true prints with current printer
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 51
Add Printing Capability to the Sticky Pad Project
Hands-On Exercise 3 Open the Sticky Pad project Display the Print Setup dialog box Display the Print Dialog box Add code and test the print header
code Add and test the print footer code Add and test the print text box code
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 52
Summary ...
Common Dialog Control gives us access to the Windows’ dialog boxes
Open and Save dialog boxes used with files Print Setup and Print dialog boxes used when
printing Color and Font dialog boxes used with fonts A class is the formal definition of an object An instance is one of the objects that belongs
to a class Text, binary, RTF and HTML file formats
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 53
Summary...Sequential access reads and writes
sequentially like a cassette tapeRandom access reads and writes much
like an audio CDBinary access reads and writes varying
record lengths, or no records at allOpen, Input, Input #, Close, Print #
statements and functions for reading and writing files
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 54
Summary
File System Object (FSO) is an object-based tool to work with drives, folders and files
Bugs can be compiler errors, runtime errors, or logic errors. Use error handling code to avoid runtime errors.
Printer Object is a device independent drawing space
Print Setup and Print dialog boxes give user more control over printing process
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 55
Practice with Visual Basic
1. Common Dialog Demo2. Print Demonstration3. ANSI Values Demo4. Clipboard Demo5. Using Extra Forms6. Printing Text7. Processing Text Demonstrations
Exploring MS Visual Basic 6
Copyright 1999 Prentice-Hall, Inc. 56
Case Studies
Personal Text EditorThe Rich Text Box ControlAsk the ProsEnhance with Extra Forms