Component 10a, Slide 1CP2030 Copyright © University of Wolverhampton
CP2030Visual Basic for C++ Programmers
Component 10
– Working with Binary Files
– Error handling
– Working with other applications
Component 10a, Slide 2CP2030 Copyright © University of Wolverhampton
Aims and objectives
Understand the structure of Binary Files Use the various techniques available in
Visual Basic to write to binary files. Understand how to “launch” and interact
with other applications from within V.B.
Component 10a, Slide 3CP2030 Copyright © University of Wolverhampton
VB data files
VB supports three kinds of data files
– Sequential files store data as ACII text. Characters are read from and stored to the file character by character
– Random-access files store data in special VB internal formats. Such files require rigid file structure
– Binary files store data as individual bytes. No file structure exists, and no special internal formats are assumed
we will look at Binary files this week
Component 10a, Slide 4CP2030 Copyright © University of Wolverhampton
Binary files
Sequential and random access files have a certain degree of organisation of the data stored within them. Whereas VB treats binary files as just a file consisting of a stream of bytes
Treating files as binary files is useful to handle and interpret files created in formats alien to VB such as spreadsheets or wordprocessors, as you can read, or alter any bytes including ones that are control characters.
VB only sees the data as bytes and so any interpretation of what the each Byte means must be written into the program
Component 10a, Slide 5CP2030 Copyright © University of Wolverhampton
Three steps to process a Binary File
Use the following three steps to process binary files
1 open the File For Binary
2 Use a record variables in Get and Put instructions to read and write the data
3 Close the file
Component 10a, Slide 6CP2030 Copyright © University of Wolverhampton
1st step - opening the file
The syntax is as follows:
Open filename For BinaryAs #filenum
where filename is the filename and path
#filenum is the filehandle number
e.g. applying this to a WORD document
Open “c:\temp\letter.doc” For Binary As #1
Component 10a, Slide 7CP2030 Copyright © University of Wolverhampton
2nd step - writing or reading to the file
We can use the Put statement to write to a binary file record and the Get statement to read from the file
It has the form
Get #filenum , startbyte , variable
Put #filenum , startbyte , variable
Put #1 , 12 , iCount
- startbyte is a numeric expression specifying the byte in the file where i/o begins - variable is any variable used to transmit or receive the data values
Component 10a, Slide 8CP2030 Copyright © University of Wolverhampton
File position pointer
A file position pointer is associated with each binary file
identifies which byte is to be written to or read from
– first byte is position 1, 2nd is number 2 and so on
can be moved to any byte in the file then read or write as many bytes as you want
If we omit startbyte with Get or Put statements then the file position pointer establishes a default value, successive Get and Put instructions adjust this value appropriately
Component 10a, Slide 9CP2030 Copyright © University of Wolverhampton
Get and Put
Get reads the necessary number of Bytes to satisfy the length of the variable e.g 2 bytes for a single, 8 for a currency and so on.
For a fixed length string or a user defined type, Get reads the number of bytes to satisfy the length of the variable. A variable-length string variable will have the same number of bytes read into it as being stored in the variable at that time.
Put writes the number of bytes equal to the length of the variable
Component 10a, Slide 10CP2030 Copyright © University of Wolverhampton
3rd step - closing the file
As with all file handling work it is important to Close the file when all i/o activity has finished
format
Close #filenum
e.g.
Close #1
Component 10a, Slide 11CP2030 Copyright © University of Wolverhampton
Seek and Loc functions
With binary files Seek and Loc functions return a file position in number of bytes from the beginning of the file. Seek returns the current file pointer and Loc returns the number of the last byte read.
E.g.
Put #4, 26, iMyAgePrint “Byte number file pointer is at is ” ; Seek (4)Print “Last byte written was number” ; Seek (4)
which gives the outputByte number file pointer is at is 28last byte written was number 27
Component 10a, Slide 12CP2030 Copyright © University of Wolverhampton
Error Handling - On Error
Probably the best way to find if a file exists is to use the ‘On Error’ statement, which catches all file related errors
On Error { GoTo line | Resume Next | GoTo 0 }
Goto Line : is either a line number or a label– e.g. On Error Goto ErrorHandler:– e.g. On Error Goto 20
Resume Next : causes next line of code to be executed, ignoring the error
Goto 0 : turns off the error handling
Component 10a, Slide 13CP2030 Copyright © University of Wolverhampton
Error Handling - Code Structure
Sub subname
declarations
code not having error handling if any .......
On Error Goto ErrorHandlingRoutineLabel
code having error handling
On Error Goto 0 ‘[Optional] turn off error handling, if required
code not having error handling if any .......
Exit Sub
ErrorHandlingRoutineLabel:
Error handling code
Resume Next ‘Resume at next line after where the error occured
End Sub
Component 10a, Slide 14CP2030 Copyright © University of Wolverhampton
Error Handling - Resume Statement
The Resume statement must be in the Error Handling routine or else an error occurs
Resume { [0] | Next | line}
Resume 0 : Program execution resumes at the line causing the error
Resume Next : Program execution resumes at the line immediately after the one causing the error
Resume Line : Either a line number or label in the main procedure where code is to resume executing
Component 10a, Slide 15CP2030 Copyright © University of Wolverhampton
Error Handling - Example
Here when the file or drive is incorrect an error occurs
Dim sMsg As String ' Declare variables.On Error GoTo ErrorHandler ' Set up error handler.Open “C:\CISFILE.TXT" For Input As #1 ' Try to open file.
‘statements.......Close #1 ' Close the file.Exit Sub ' Exit before entering
ErrorHandler: ' Error handlerMsgbox “Error in Opening File”, ,”File Access Error”Resume Next ' Resume procedure.
End Sub
Component 10a, Slide 16CP2030 Copyright © University of Wolverhampton
Error Handling - Err and Error()
The ‘Err’ statement is the error number returned from the last error to occur
For full list see “Trappable Errors” on Help File errors in range 52-76; e.g.
– 53 File not found– 61 Disk full
Other common errors– 9 Subscript out of range– 11 Division by zero
The ‘Error(ErrorNumber) statement returns a message describing the specified error number
Component 10a, Slide 17CP2030 Copyright © University of Wolverhampton
Improved Error Handling
An improved message for the message box in the error handling routine could then be
ErrorHandler: ' Error handlerMsgbox Error(Err), ,”File Access Error”Resume Next ' Resume procedure.
End Sub
Here the message could be ‘file not found’ or ‘File already open’ etc.
Component 10a, Slide 18CP2030 Copyright © University of Wolverhampton
Error Handling, continued
For a comprehensive error handling section:
ErrorHandler: Select Case Err Case 58: MsgBox Error(Err),,”File Access Error” …….. ‘Code to allow user to
“browse”for filename …….. ‘ then open valid file. Case 61: MsgBox Error(Err),,”Replace with new
disk” …….. End Select
Component 10a, Slide 19CP2030 Copyright © University of Wolverhampton
Use the power of existing applications…...
Why write ‘Edit’ or ‘Print’ functionality into your VB programwhen Microsoft have already done it for you withNOTEPAD (or WORD).
Similarly, why re-invent the ‘Spreadsheet’ ??
BUT…. several pitfalls…..requires some experimentation to get it right. Try it !…………………… . . . . .
Component 10a, Slide 20CP2030 Copyright © University of Wolverhampton
A simple way to use other applications…
Shell ( commandstring [,windowstyle] )egShell (NOTEPAD)orShell (NOTEPAD , 2)
Commandstring = name of executable, batchfile etc .exe assumed but could be .bat .com .pif not case sensitive, BUT must be EXACT name of package
Shell starts package ASYNCHRONOUSLY…care!!
Component 10a, Slide 21CP2030 Copyright © University of Wolverhampton
windowstyle …..
1 = Normal with focus2 = Minimised with focus (default)etc….see help for full list.
Component 10a, Slide 22CP2030 Copyright © University of Wolverhampton
…but then you often give the shelled application the focus…….
AppActivate applicationhandleeg
AppActivate applicationhandle
an example should help (see later)…………..
Component 10a, Slide 23CP2030 Copyright © University of Wolverhampton
When application running…SENDKEYS
SendKeys keystring [ , wait ]egSendKeys “Computing”or SendKeys “ABC”, TRUE
wait can be true or false (default=false). Specifiesthat execution of calling procedure will not continueUNTIL ‘other’ application/package has consumed thesekeys.
Component 10a, Slide 24CP2030 Copyright © University of Wolverhampton
‘Special’ keys each have unique name eg
{UP} is up arrow key, {ESC} is escape etcNote braces{}…….see help for full list
Shifted keys are achieved by using ‘prefix’ codes, eg
SendKeys +{ESC} sends Shift plus EscapeNote… + = shift ^ = control %=alt etc
Component 10a, Slide 25CP2030 Copyright © University of Wolverhampton
Repeated keys are easy………
SendKeys {key repeats}eg
Sendkeys {LEFT 40} sends 40 presses of Left arrow key
Component 10a, Slide 26CP2030 Copyright © University of Wolverhampton
A couple of examples…...
nfile = File1.ListCount Rem assume your app. uses a FILELIST control crlf$ = Chr$(13) + Chr$(10) Rem put required text into clipboard Clipboard.Clear For a = 0 To nfile - 1 txt$ = File1.List(a) Clipboard.SetText (Clipboard.GetText() + crlf$ + txt$) Next a continued next slide………….
Component 10a, Slide 27CP2030 Copyright © University of Wolverhampton
txt$ = "Notepad" MyAppID = Shell(txt$, 1): Rem start NOTEPAD Rem crude way of giving it time to execute Rem DOEVENT would be better (see help) t = Timer: Do: Loop Until Timer > t + 0.5 Or Timer < 10 AppActivate MyAppID: Rem give NOTEPAD the focus
SendKeys "%E": Rem send ALT+E ie select 'EDIT' menu SendKeys "P": Rem send 'P' ie 'PASTE' text currently in clipboard
done.
Component 10a, Slide 28CP2030 Copyright © University of Wolverhampton
An example NOT using clipboard….
Rem start NOTEPAD with a specified ASCII file txt$ = "Notepad \MYFILE.TXT" MyAppID = Shell(txt$, 1) t = Timer: Do: Loop Until Timer > t + 0.5 Or Timer < 10 AppActivate MyAppID
Component 10a, Slide 29CP2030 Copyright © University of Wolverhampton
Summary
We have investigated– Binary files
the file structure of the binary file type how we can map reading and writing to a
binary file using the Get and Put statement the use of the Seek and Loc functions to
determine the present or last byte position of the file position pointer.
– How to trap and handle errors
– Interacting with other applications