Sign In | Sign Up

My Profile

OmegaRed07
7482
.....
Points: 49
Gender: Male

Shortcuts

Categories

Post

Visual Basic 6.0 "2" (Notes, Tircks and Tips)
Size: Large, Medium, Small Sat Jul 4, 09 08:57 AM | Category: All
2
Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4

VB - Error handling and Debugging and File Input/Output

 

Error Handling enables programmers to write clearer, more robust, more fault-tolerant programs. Error handling enables the programmer to attempt to recover (i.e., continue executing) from infrequent fatal errors rather than letting them occur and suffering the consequences (such as loss of application data). If an error is severe and recovery is not possible, the program can be exited "gracefully"-all files can be closed and notification can be given that the program is terminating. The recovery code is called an error handler.

Error handling is designed for dealing with synchronous errors such as an attempt to divide by 0 (that occurs as the program executes the divide instruction). Other common examples of synchronous errors are memory exhaustion, an out-of-bound array index, and arithmetic overflow. Error handling provides the programmer with a disciplined set of capabilities for dealing with these types of errors.

Error-handling code varies in nature and amount among software systems depending on the application and whether or not the software is a product for release. Products tend to contain much more error-handling code than is contained in "casual" software.

Usually, error-handling code is interspersed throughout a program's code. Errors are dealt with the places in the code where errors are likely to occur. The advantage of this approach is that a programmer reading the code can see the error handling in the immediate vicinity of the code and determine if the proper error handling has been implemented.

The problem with the scheme is that code in a sense becomes "polluted" with error handling. It becomes difficult for a programmer concerned with the application itself to read the code and determine if the code is working is correctly. Error handling often makes the code more difficult to understand and maintain.

When Error Handling should be used

Error handling should be used to process only exceptional situations, despite the fact that there is nothing to prevent that programmer from using errors as an alternate form of program control.

This lesson explains about error handling and debugging in easy steps with quick examples. For more in-depth lessons in Error Handling click here

Error-Handling, Debugging - Error Types

 

• No matter how hard we try, errors do creep into our programs. These errors can be grouped into three categories:

1.             Syntax errors

2.             Run-time errors

3.             Logic errors

• Syntax errors occur when you mistype a command or leave out an expected phrase or argument. Visual Basic detects these errors as they occur and even provides help in correcting them. You cannot run a Visual Basic program until all syntax errors have been corrected.

• Run-time errors are usually beyond your program's control. Examples include: when a variable takes on an unexpected value (divide by zero), when a drive door is left open, or when a file is not found. Visual Basic allows you to trap such errors and make attempts to correct them.

• Logic errors are the most difficult to find. With logic errors, the program will usually run, but will produce incorrect or unexpected results. The Visual Basic debugger is an aid in detecting logic errors.

• Some ways to minimize errors:

·                     Design your application carefully. More design time means less debugging time.

·                     Use comments where applicable to help you remember what you were trying to do.

  •  
    • Use consistent and meaningful naming conventions for your variables, objects, and procedures.

 

·         Error-Handling, Debugging - Run-Time Error Trapping and Handling

 

 

·         • Run-time errors are trappable. That is, Visual Basic recognizes an error has occurred and enables you to trap it and take corrective action. If an error occurs and is not trapped, your program will usually end in a rather unceremonious manner.

• Error trapping is enabled with the On Error statement:

·         On Error GoTo errlabel

·         Yes, this uses the dreaded GoTo statement! Any time a run-time error occurs following this line, program control is transferred to the line labeled errlabel. Recall a labeled line is simply a line with the label followed by a colon (:).

·         • The best way to explain how to use error trapping is to look at an outline of an example procedure with error trapping.

·         Sub SubExample()

[Declare variables, ...]

On Error GoTo HandleErrors

[Procedure code]

Exit Sub
HandleErrors:

Error handling code]

End Sub

·         Once you have set up the variable declarations, constant definitions, and any other procedure preliminaries, the On Error statement is executed to enable error trapping. Your normal procedure code follows this statement. The error handling code goes at the end of the procedure, following the HandleErrors statement label. This is the code that is executed if an error is encountered anywhere in the Sub procedure. Note you must exit (with Exit Sub) from the code before reaching the HandleErrors line to avoid inadvertent execution of the error handling code.

·         • Since the error handling code is in the same procedure where an error occurs, all variables in that procedure are available for possible corrective action. If at some time in your procedure, you want to turn off error trapping, that is done with the following statement:

·         On Error GoTo 0

·         • Once a run-time error occurs, we would like to know what the error is and attempt to fix it. This is done in the error handling code.

·         • Visual Basic offers help in identifying run-time errors. The Err object returns, in its Number property (Err.Number), the number associated with the current error condition. (The Err function has other useful properties that we won’t cover here - consult on-line help for further information.) The Error() function takes this error number as its argument and returns a string description of the error. Consult on-line help for Visual Basic run-time error numbers and their descriptions.

·         • Once an error has been trapped and some action taken, control must be returned to your application. That control is returned via the Resume statement. There are three options:

·         Resume Lets you retry the operation that caused the error. That is, control is returned to the line where the error occurred. This could be dangerous in that, if the error has not been corrected (via code or by the user), an infinite loop between the error handler and the procedure code may result.

·         Resume Next Program control is returned to the line immediately following the line where the error occurred.
Resume label Program control is returned to the line labeled label.

·         • Be careful with the Resume statement. When executing the error handling portion of the code and the end of the procedure is encountered before a Resume, an error occurs. Likewise, if a Resume is encountered outside of the error handling portion of the code, an error occurs.

 

Error-Handling, Debugging - General Error Handling Procedure

 

• Development of an adequate error handling procedure is application dependent. You need to know what type of errors you are looking for and what corrective actions must be taken if these errors are encountered. For example, if a 'divide by zero' is found, you need to decide whether to skip the operation or do something to reset the offending denominator.

• What we develop here is a generic framework for an error handling procedure. It simply informs the user that an error has occurred, provides a description of the error, and allows the user to Abort, Retry, or Ignore. This framework is a good starting point for designing custom error handling for your applications.

• The generic code (begins with label HandleErrors) is:

HandleErrors:
Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number))

Case vbAbort
   Resume ExitLine
Case vbRetry
   Resume
Case vbIgnore
   Resume Next

End Select
ExitLine:
Exit Sub

Let’s look at what goes on here. First, this routine is only executed when an error occurs. A message box is displayed, using the Visual Basic provided error description [Error(Err.Number)] as the message, uses a critical icon along with the Abort, Retry, and Ignore buttons, and uses the error number [Err.Number] as the title. This message box returns a response indicating which button was selected by the user.

If Abort is selected, we simply exit the procedure. (This is done using a Resume to the line labeled ExitLine. Recall all error trapping must be terminated with a Resume statement of some kind.)

If Retry is selected, the offending program line is retried (in a real application, you or the user would have to change something here to correct the condition causing the error).

If Ignore is selected, program operation continues with the line following the error causing line.

• To use this generic code in an existing procedure, you need to do three things:

1.             Copy and paste the error handling code into the end of your procedure.

2.             Place an Exit Sub line immediately preceding the HandleErrors labeled line.

3.             Place the line, On Error GoTo HandleErrors, at the beginning of your procedure.

For example, if your procedure is the SubExample seen earlier, the modified code will look like this:

Sub SubExample()
   .
   . [Declare variables, ...]
   . 
On Error GoTo HandleErrors
   .
   . [Procedure code]
   .
Exit Sub
HandleErrors:
Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number))
Case vbAbort
   Resume ExitLine
Case vbRetry
   Resume
Case vbIgnore
   Resume Next

End Select
ExitLine:
Exit Sub
End Sub

Again, this is a very basic error-handling routine. You must determine its utility in your applications and make any modifications necessary. Specifically, you need code to clear error conditions before using the Retry option.

• One last thing. Once you've written an error handling routine, you need to test it to make sure it works properly. But, creating run-time errors is sometimes difficult and perhaps dangerous. Visual Basic comes to the rescue! The Visual Basic Err object has a method (Raise) associated with it that simulates the occurrence of a run-time error. To cause an error with value Number, use:

Err.Raise Number

• We can use this function to completely test the operation of any error handler we write. Don’t forget to remove the Raise statement once testing is completed, though! And, to really get fancy, you can also use Raise to generate your own ‘application-defined’ errors. There are errors specific to your application that you want to trap.

• To clear an error condition (any error, not just ones generated with the Raise method), use the method Clear:

Err.Clear

 

·         Error-Handling, Debugging - Example - Simple Error Trapping

 

·         1. Start a new project. Add a text box and a command button.

2. Set the properties of the form and each control:

Form1:
BorderStyle - 1-Fixed Single
Caption - Error Generator
Name frmError

Command1:
Caption - Generate Error
Default - True
Name - cmdGenError

Text1:
Name - txtError
Text - [Blank]

The form should look something like this:

http://visualbasic.freetutes.com/learn-vb6/images/fig21.1.jpg

3. Attach this code to the cmdGenError_Click event.

Private Sub cmdGenError_Click()
On Error GoTo HandleErrors
Err.Raise Val(txtError.Text)
Err.Clear
Exit Sub

HandleErrors:
Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number))

Case vbAbort
  Resume ExitLine
Case vbRetry
  Resume
Case vbIgnore
  Resume Next
End Select

ExitLine:

Exit Sub
End Sub

In this code, we simply generate an error using the number input in the text box. The generic error handler then displays a message box which you can respond to in one of three ways.

4. Save your application. Try it out using some of these typical error numbers (or use numbers found with on-line help). Notice how program control changes depending on which button is clicked.

·         Error Number    Error Description

6                       Overflow
9                       Subscript out of range
11                     Division by zero
13                     Type mismatch
16                     Expression too complex
20                     Resume without error
52                     Bad file name or number
53                     File not found
55                     File already open
61                     Disk full
70                     Permission denied

·         92                     For loop not initialized

Error-Handling, Debugging - Debugging Visual Basic Programs

 

• We now consider the search for, and elimination of, logic errors. These are errors that don’t prevent an application from running, but cause incorrect or unexpected results. Visual Basic provides an excellent set of debugging tools to aid in this search.

• Debugging a code is an art, not a science. There are no prescribed processes that you can follow to eliminate all logic errors in your program. The usual approach is to eliminate them as they are discovered.

• What we’ll do here is present the debugging tools available in the Visual Basic environment (several of which appear as buttons on the toolbar) and describe their use with an example. You, as the program designer, should select the debugging approach and tools you feel most comfortable with.

• The interface between your application and the debugging tools is via three different debug windows: the Immediate Window, the Locals Window, and the Watch Window. These windows can be accessed from the View menu (the Immediate Window can be accessed by pressing Ctrl+G). Or, they can be selected from the Debug Toolbar (accessed using the Toolbars option under the View menu):


http://visualbasic.freetutes.com/learn-vb6/images/fig21.2.jpg

• All debugging using the debug windows is done when your application is in break mode. You can enter break mode by setting breakpoints, pressing Ctrl+Break, or the program will go into break mode if it encounters an untrapped error or a Stop statement.

• Once in break mode, the debug windows and other tools can be used to:

1.             Determine values of variables

2.             Set breakpoints

3.             Set watch variables and expressions

4.             Manually control the application

5.             Determine which procedures have been called

6.             Change the values of variables and properties

Example - Debugging

1. Unlike other examples, we’ll do this one as a group. It will be used to demonstrate use of the debugging tools.

2. The example simply has a form with a single command button. The button is used to execute some code. We won’t be real careful about proper naming conventions and such in this example.

http://visualbasic.freetutes.com/learn-vb6/images/fig21.3.jpg

3. The code attached to this button’s Click event is a simple loop that evaluates a function at several values.

Private Sub Command1_Click()
Dim X As Integer, Y As Integer
X = 0
Do
Y = Fcn(X)
X = X + 1
Loop While X <= 20
End Sub

This code begins with an X value of 0 and computes the Y value using the general integer function Fcn. It then increments X by 1 and repeats the Loop. It continues looping While X is less than or equal to 20. The function Fcn is computed using:

Function Fcn(X As Integer) As Integer
Fcn = CInt(0.1 * X ^ 2)
End Function

Admittedly, this code doesn’t do much, especially without any output, but it makes a good example for looking at debugger use. Set up the application and get ready to try debugging.

 

Using the Debugging Tools

 

• There are several debugging tools available for use in Visual Basic. Access to these tools is provided with both menu options and buttons on the Debug toolbar. These tools include breakpoints, watch points, calls, step into, step over, and step out.

• The simplest tool is the use of direct prints to the immediate window.

• Printing to the Immediate Window:

http://visualbasic.freetutes.com/learn-vb6/images/fig21.4.jpg

You can print directly to the immediate window while an application is running. Sometimes, this is all the debugging you may need. A few carefully placed print statements can sometimes clear up all logic errors, especially in small applications.

To print to the immediate window, use the Print method:

Debug.Print [List of variables separated by commas or semi-colons]

• Debug.Print Example:

1.             Place the following statement in the Command1_Click procedure after the line calling the general procedure Fcn:

Debug.Print X; Y

and run the application.

2.             Examine the immediate window. Note how, at each iteration of the loop, the program prints the value of X and Y. You could use this information to make sure X is incrementing correctly and that Y values look acceptable.

3.             Remove the Debug.Print statement.

• Breakpoints:

http://visualbasic.freetutes.com/learn-vb6/images/fig21.5.jpg

In the above examples, the program ran to completion before we could look at the debug window. In many applications, we want to stop the application while it is running, examine variables and then continue running. This can be done with breakpoints.

A breakpoint is a line in the code where you want to stop (temporarily) the execution of the program, that is force the program into break mode. To set a breakpoint, put the cursor in the line of code you want to break on. Then, press <F9> or click the Breakpoint button on the toolbar or select Toggle Breakpoint from the Debug menu. The line will be highlighted.

When you run your program, Visual Basic will stop when it reaches lines with breakpoints and allow you to use the immediate window to check variables and expressions. To continue program operation after a breakpoint, press <F5>, click the Run button on the toolbar, or choose Start from the Run menu.

You can also change variable values using the immediate window. Simply type a valid Basic expression. This can sometimes be dangerous, though, as it may change program operation completely.

• Breakpoint Example:

1.             Set a breakpoint on the X = X + 1 line in the sample program. Run the program.

2.             When the program stops, display the immediate window and type the following line:

Print X;Y

3.             The values of these two variables will appear in the debug window. You can use a question mark (?) as shorthand for the command Print, if you’d like. Restart the application. Print the new variable values.

4.             Try other breakpoints if you have time. Once done, all breakpoints can be cleared by Ctrl+Shift+<F9> or by choosing Clear All Breakpoints from the Debug menu. Individual breakpoints can be toggled using <F9> or the Breakpoint button on the toolbar.

• Viewing Variables in the Locals Window:

http://visualbasic.freetutes.com/learn-vb6/images/fig21.6.jpg

The locals window shows the value of any variables within the scope of the current procedure. As execution switches from procedure to procedure, the contents of this window changes to reflect only the variables applicable to the current procedure. Repeat the above example and notice the values of X and Y also appear in the locals window.

• Watch Expressions:

http://visualbasic.freetutes.com/learn-vb6/images/fig21.7.jpg

The Add Watch option on the Debug menu allows you to establish watch expressions for your application. Watch expressions can be variable values or logical expressions you want to view or test. Values of watch expressions are displayed in the watch window.

In break mode, you can use the Quick Watch button on the toolbar to add watch expressions you need. Simply put the cursor on the variable or expression you want to add to the watch list and click the Quick Watch button.

Watch expressions can be edited using the Edit Watch option on the Debug menu.

• Watch Expression Example:

1.             Set a breakpoint at the X = X + 1 line in the example.

2.             Set a watch expression for the variable X. Run the application. Notice X appears in the watch window. Every time you re-start the application, the value of X changes.

3.             At some point in the debug procedure, add a quick watch on Y. Notice it is now in the watch window.

4.             Clear the breakpoint. Add a watch on the expression: X = Y. Set Watch Type to ‘Break When Value Is True.’ Run the application. Notice it goes into break mode and displays the watch window whenever X = Y. Delete this last watch expression.

• Call Stack:

http://visualbasic.freetutes.com/learn-vb6/images/fig21.8.jpg

Selecting the Call Stack button from the toolbar (or pressing Ctrl+L or selecting Call Stack from the View menu) will display all active procedures, that is those that have not been exited.

Call Stack helps you unravel situations with nested procedure calls to give you some idea of where you are in the application.

• Call Stack Example:

1.             Set a breakpoint on the Fcn = Cint() line in the general function procedure. Run the application. It will break at this line.

2.             Press the Call Stack button. It will indicate you are currently in the Fcn procedure which was called from the Command1_Click procedure. Clear the breakpoint.

• Single Stepping (Step Into):

http://visualbasic.freetutes.com/learn-vb6/images/fig21.9.jpg

While at a breakpoint, you may execute your program one line at a time by pressing <F8>, choosing the Step Into option in the Debug menu, or by clicking the Step Into button on the toolbar.

This process is single stepping. It allows you to watch how variables change (in the locals window) or how your form changes, one step at a time.

You may step through several lines at a time by using Run To Cursor option. With this option, click on a line below your current point of execution. Then press Ctrl+<F8> (or choose Run To Cursor in the Debug menu). the program will run through every line up to the cursor location, then stop.

• Step Into Example:

1.             Set a breakpoint on the Do line in the example. Run the application.

2.             When the program breaks, use the Step Into button to single step through the program.

3.             At some point, put the cursor on the Loop While line. Try the Run To Cursor option (press Ctrl+<F8>).

•Procedure Stepping (Step Over):

http://visualbasic.freetutes.com/learn-vb6/images/fig21.10.jpg

While single stepping your program, if you come to a procedure call you know functions properly, you can perform procedure stepping. This simply executes the entire procedure at once, rather than one step at a time.

To move through a procedure in this manner, press Shift+<F8>, choose Step Over from the Debug menu, or press the Step Over button on the toolbar.

• Step Over Example:

1.             Run the previous example. Single step through it a couple of times.

2.             One time through, when you are at the line calling the Fcn function, press the Step Over button. Notice how the program did not single step through the function as it did previously.

• Function Exit (Step Out):

http://visualbasic.freetutes.com/learn-vb6/images/fig21.11.jpg

While stepping through your program, if you wish to complete the execution of a function you are in, without stepping through it line-by-line, choose the Step Out option. The function will be completed and you will be returned to the procedure accessing that function.

To perform this step out, press Ctrl+Shift+<F8>, choose Step Out from the Debug menu, or press the Step Out button on the toolbar. Try this on the previous example.

Debugging Strategies

 

• We’ve looked at each debugging tool briefly. Be aware this is a cursory introduction. Use the on-line help to delve into the details of each tool described. Only through lots of use and practice can you become a proficient debugger. There are some guidelines to doing a good job, though.

• My first suggestion is: keep it simple. Many times, you only have one or two bad lines of code. And you, knowing your code best, can usually quickly narrow down the areas with bad lines. Don’t set up some elaborate debugging procedure if you haven’t tried a simple approach to find your error(s) first. Many times, just a few intelligently-placed Debug.Print statements or a few examinations of the immediate and locals windows can solve your problem.

• A tried and true approach to debugging can be called Divide and Conquer. If you’re not sure where your error is, guess somewhere in the middle of your application code. Set a breakpoint there. If the error hasn’t shown up by then, you know it’s in the second half of your code. If it has shown up, it’s in the first half. Repeat this division process until you’ve narrowed your search.

• And, of course, the best debugging strategy is to be careful when you first design and write your application to minimize searching for errors later.

Sequential Files

• In many applications, it is helpful to have the capability to read and write information to a disk file. This information could be some computed data or perhaps information loaded into a Visual Basic object.

• Visual Basic supports two primary file formats: sequential and random access. We first look at sequential files.

• A sequential file is a line-by-line list of data. You can view a sequential file with any text editor. When using sequential files, you must know the order in which information was written to the file to allow proper reading of the file.

• Sequential files can handle both text data and variable values. Sequential access is best when dealing with files that have lines with mixed information of different lengths. I use them to transfer data between applications.

 

Sequential File Output (Variables)

 

• We first look at writing values of variables to sequential files. The first step is to Open a file to write information to. The syntax for opening a sequential file for output is:

Open SeqFileName For Output As #N

where SeqFileName is the name of the file to open and N is an integer file number. The filename must be a complete path to the file.

• When done writing to the file, Close it using:

Close N

Once a file is closed, it is saved on the disk under the path and filename used to open the file.

• Information is written to a sequential file one line at a time. Each line of output requires a separate Basic statement.

• There are two ways to write variables to a sequential file. The first uses the Write statement:

Write #N, [variable list]

where the variable list has variable names delimited by commas. (If the variable list is omitted, a blank line is printed to the file.) This statement will write one line of information to the file, that line containing the variables specified in the variable list. The variables will be delimited by commas and any string variables will be enclosed in quotes. This is a good format for exporting files to other applications like Excel.

Example

Dim A As Integer, B As String, C As Single, D As Integer
.
.
Open TestOut For Output As #1
Write #1, A, B, C
Write #1, D
Close 1

After this code runs, the file TestOut will have two lines. The first will have the variables A, B, and C, delimited by commas, with B (a string variable) in quotes. The second line will simply have the value of the variable D.

• The second way to write variables to a sequential file is with the Print statement:

Print #N, [variable list]

This statement will write one line of information to the file, that line containing the variables specified in the variable list. (If the variable list is omitted, a blank line will be printed.) If the variables in the list are separated with semicolons (;), they are printed with a single space between them in the file. If separated by commas (,), they are spaced in wide columns. Be careful using the Print statement with string variables. The Print statement does not enclose string variables in quotes, hence, when you read such a variable back in, Visual Basic may have trouble knowing where a string ends and begins. It’s good practice to ‘tack on’ quotes to string variables when using Print.

Example

Dim A As Integer, B As String, C As Single, D As Integer
.
.
Open TestOut For Output As #1
Print #1, A; Chr(34) + B + Chr(34), C
Print #1, D
Close 1

After this code runs, the file TestOut will have two lines. The first will have the variables A, B, and C, delimited by spaces. B will be enclosed by quotes [Chr(34)]. The second line will simply have the value of the variable D.

Quick Example: Writing Variables to Sequential Files

1.             Start a new project.

2.             Attach the following code to the Form_Load procedure. This code simply writes a few variables to sequential files.

Private Sub Form_Load()
Dim A As Integer, B As String, C As Single, D As Integer
A = 5
B = "Visual Basic"
C = 2.15
D = -20
Open "Test1.Txt" For Output As #1
Open "Test2.Txt" For Output As #2
Write #1, A, B, C
Write #1, D
Print #2, A, B, C
Print #2, D
Close 1
Close 2
End Sub

3.             Run the program. Use a text editor (try the Windows 95 Notepad) to examine the contents of the two files, Test1.Txt and Test2.Txt. They are probably in the Visual Basic main directory. Note the difference in the two files, especially how the variables are delimited and the fact that the string variable is not enclosed in quotes in Test2.Txt. Save the application, if you want to.

Sequential File Input (Variables)

 

• To read variables from a sequential file, we essentially reverse the write procedure. First, open the file using:

Open SeqFileName For Input As #N

where N is an integer file number and SeqFileName is a complete file path. The file is closed using:

Close N

• The Input statement is used to read in variables from a sequential file. The format is:

Input #N, [variable list]

The variable names in the list are separated by commas. If no variables are listed, the current line in the file N is skipped.

• Note variables must be read in exactly the same manner as they were written. So, using our previous example with the variables A, B, C, and D, the appropriate statements are:

Input #1, A, B, C
Input #1, D

These two lines read the variables A, B, and C from the first line in the file and D from the second line. It doesn’t matter whether the data was originally written to the file using Write or Print (i.e. commas are ignored).


Quick Example: Reading Variables from Sequential Files

1.             Start a new project or simply modify the previous quick example.

2.             Attach the following code to the Form_Load procedure. This code reads in files created in the last quick example.

Private Sub Form_Load()
Dim A As Integer, B As String, C As Single, D As Integer
Open "Test1.Txt" For Input As #1
Input #1, A, B, C
Debug.Print "A="; A
Debug.Print "B="; B
Debug.Print "C="; C
Input #1, D
Debug.Print "D="; D
Close 1
End Sub

Note the
Debug.Print statements and how you can add some identifiers (in quotes) for printed information.

3.             Run the program. Look in the debug window and note the variable values. Save the application, if you want to.

4.             Rerun the program using Test2.Txt as in the input file. What differences do you see? Do you see the problem with using Print and string variables? Because of this problem, I almost always use Write (instead of Print) for saving variable information to files. Edit the Test2.Txt file (in Notepad), putting quotes around the words Visual Basic. Rerun the program using this file as input - it should work fine now.

Writing and Reading Text Using Sequential Files

 

• In many applications, we would like to be able to save text information and retrieve it for later reference. This information could be a text file created by an application or the contents of a Visual Basic text box.

• Writing Text Files:

To write a sequential text file, we follow the simple procedure: open the file, write the file, close the file. If the file is a line-by-line text file, each line of the file is written to disk using a single Print statement:

Print #N, Line

where Line is the current line (a text string). This statement should be in a loop that encompasses all lines of the file. You must know the number of lines in your file, beforehand.

If we want to write the contents of the Text property of a text box named txtExample to a file, we use:

Print #N, txtExample.Text

Example

We have a text box named txtExample. We want to save the contents of the Text property of that box in a file named MyText.ned on the c: drive in the \MyFiles directory. The code to do this is:

Open “c:\MyFiles\MyText.ned” For Output As #1
Print #1, txtExample.Text
Close 1

The text is now saved in the file for later retrieval.

• Reading Text Files:

To read the contents of a previously-saved text file, we follow similar steps to the writing process: open the file, read the file, close the file. If the file is a text file, we read each individual line with the Line Input command:

Line Input #1, Line

This line is usually placed in a Do/Loop structure that is repeated untill all lines of the file are read in. The EOF() function can be used to detect an end-of-file condition, if you don’t know, a prioiri, how many lines are in the file.

To place the contents of a file opened with number N into the Text property of a text box named txtExample we use the Input function:

txtExample.Text = Input(LOF(N), N)

This Input function has two arguments: LOF(N), the length of the file opened as N and N, the file number.

Example

We have a file named MyText.ned stored on the c: drive in the \MyFiles directory. We want to read that text file into the text property of a text box named txtExample. The code to do this is:

Open “c:\MyFiles\MyText.ned” For Input As #1
txtExample.Text = Input(LOF(1), 1)
Close 1

The text in the file will now be displayed in the text box.

User-Defined Variables

• Data used with random access files is most often stored in user-defined variables. These data types group variables of different types into one assembly with a single, user-defined type associated with the group. Such types significantly simplify the use of random access files.

• The Visual Basic keyword Type signals the beginning of a user-defined type declaration and the words End Type signal the end. An example best illustrates establishing a user-defined variable. Say we want to use a variable that describes people by their name, their city, their height, and their weight. We would define a variable of Type Person as follows:

Type Person
Name As String
City As String
Height As Integer
Weight As Integer
End Type

These variable declarations go in the same code areas as normal variable declarations, depending on desired scope. At this point, we have not reserved any storage for the data. We have simply described to Visual Basic the layout of the data.

• To create variables with this newly defined type, we employ the usual Dim statement. For our Person example, we would use:

Dim Lou As Person
Dim John As Person
Dim Mary As Person

And now, we have three variables, each containing all the components of the variable type Person. To refer to a single component within a user-defined type, we use the dot-notation:

VarName.Component

As an example, to obtain Lou’s Age, we use:

Dim AgeValue as Integer
.
.
AgeValue = Lou.Age

Note the similarity to dot-notation we’ve been using to set properties of various Visual Basic tools.

Writing and Reading Random Access Files

 

• We look at writing and reading random access files using a user-defined variable. For other variable types, refer to Visual Basic on-line help. To open a random access file named RanFileName, use:

Open RanFileName For Random As #N Len = RecordLength

where N is an available file number and RecordLength is the length of each record. Note you don’t have to specify an input or output mode. With random access files, as long as they’re open, you can write or read to them.

• To close a random access file, use:

Close N

• As mentioned previously, the record length is the sum of the lengths of all variables that make up a record. A problem arises with String type variables. You don’t know their lengths ahead of time. To solve this problem, Visual Basic lets you declare fixed lengths for strings. This allows you to determine record length. If we have a string variable named StrExample we want to limit to 14 characters, we use the declaration:

Dim StrExample As String * 14

Recall each character in a string uses 1 byte, so the length of such a variable is 14 bytes.

• Recall our example user-defined variable type, Person. Let’s revisit it, now with restricted string lengths:

Type Person
Name As String * 40
City As String * 35
Height As Integer
Weight As Integer
End Type

The record length for this variable type is 79 bytes (40 + 35 +2 + 2). To open a file named PersonData as File #1, with such records, we would use the statement:

Open PersonData For Random As #1 Len = 79

• The Get and Put statements are used to read from and write to random access files, respectively. These statements read or write one record at a time. The syntax for these statements is simple:

Get #N, [RecordNumber], variable

Put #N, [RecordNumber], variable

The Get statement reads from the file and stores data in the variable, whereas the Put statement writes the contents of the specified variable to the file. In each case, you can optionally specifiy the record number. If you do not specify a record number, the next sequential position is used.

• The variable argument in the Get and Put statements is usually a single user-defined variable. Once read in, you obtain the component parts of this variable using dot-notation. Prior to writing a user-defined variable to a random access file, you ‘load’ the component parts using the same dot-notation.

• There’s a lot more to using random access files; we’ve only looked at the basics. Refer to your Visual Basic documentation and on-line help for further information. In particular, you need to do a little cute programming when deleting records from a random access file or when ‘resorting’ records.

Using the Open and Save Common Dialog Boxes

 

• Note to both write and read sequential and random access files, we need a file name for the Open statement. To ensure accuracy and completeness, it is suggested that common dialog boxes be used to get this file name information from the user. I’ll provide you with a couple of code segments that do just that. Both segments assume you have a common dialog box on your form named cdlFiles, with the CancelError property set equal to True. With this property True, an error is generated by Visual Basic when the user presses the Cancel button in the dialog box. By trapping this error, it allows an elegant exit from the dialog box when canceling the operation is desired.

•The code segment to obtain a file name (MyFileName with default extension Ext) for opening a file to read is:

Dim MyFileName As String, Ext As String
.
.
cdlFiles.Filter = "Files (*." + Ext + ")|*." + Ext
cdlFiles.DefaultExt = Ext
cdlFiles.DialogTitle = "Open File"
cdlFiles.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist
On Error GoTo No_Open
cdlFiles.ShowOpen
MyFileName = cdlFiles.filename
.
.
Exit Sub
No_Open:
Resume ExitLIne
ExitLine:
Exit Sub
End Sub

A few words on what’s going on here. First, some properties are set such that only files with Ext (a three letter string variable) extensions are displayed (Filter property), the default extension is Ext (DefaultExt property), the title bar is set (DialogTitle property), and some Flags are set to insure the file and path exist (see Appendix II for more common dialog flags).

Error trapping is enabled to trap the Cancel button. Finally, the common dialog box is displayed and the filename property returns with the desired name. That name is put in the string variable MyFileName. What you do after obtaining the file name depends on what type of file you are dealing with. For sequential files, you would open the file, read in the information, and close the file. For random access files, we just open the file here. Reading and writing to/from the file would be handled elsewhere in your coding.

•The code segment to retrieve a file name (MyFileName) for writing a file is:

Dim MyFileName As String, Ext As String
.
.
cdlFiles.Filter = "Files (*." + Ext + ")|*." + Ext
cdlFiles.DefaultExt = Ext
cdlFiles.DialogTitle = "Save File"
cdlFiles.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist
On Error GoTo No_Save
cdlFiles.ShowSave
MyFileName = cdlFiles.filename
.
.
Exit Sub
No_Save:
Resume ExitLine
ExitLine:
Exit Sub
End Sub

Note this code is essentially the same used for an Open file name. The Flags property differs slightly. The user is prompted if a previously saved file is selected for overwrite. After obtaining a valid file name for a sequential file, we would open the file for output, write the file, and close it. For a random access file, things are trickier.

If we want to save the file with the same name we opened it with, we simply close the file. If the name is different, we must open a file (using a different number) with the new name, write the complete random access file, then close it. Like I said, it’s trickier.

•We use both of these code segments in the final example where we write and read sequential files.

 


Link: http://blog.bitcomet.com/foxhound007/post_101674/ ©
Add to favorites | Quote Reads (819) | Comments (1)

Related Posts

CommentsReload

koyotee39 Sat Jul 4, 09 03:22 PM

HI GOOD POST VOTED



TOP