Visual basic sequential files




















Sequential File Processing Statements and Functions. Processing a Comma-Delimited File. Visual Basic provides the capability of processing three types of files:. The next several topics address VB's sequential file processing capabilities. Binary and Random files will be covered in later topics. The following sequential file-related statements and functions will be discussed:. Prepares a file to be processed by the VB program. Supplies a file number that is not already in use.

Reads fields from a comma-delimited sequential file. Reads a line up to the carriage return from a sequential file. Writes fields to a sequential file in comma-delimited format. Writes a formatted line of output to a sequential file. As you know, a data file consists of records, which consist of fields. The file that will be used for all examples in this section is a simplified employee file, which consists of the following fields:.

Suppose there were five records in the file. A graphic representation of the file populated with the five data records follows the field names are not stored in the file :. Please note that the data types for these fields are the data types of the variables into which these fields will be stored.

On the sequential file, all fields will be represented as a string of characters. Following are three different ways that the data in this sequential file might be stored; for example, if you opened up a sequential data file in a text editor such as Notepad, this is what you might see. Each field is separated by a comma. Both string and numeric fields are "trimmed" contain no extraneous spaces or zeroes.

String fields are enclosed in quotes Note: The quotes enclosing the string fields are optional, VB and other applications that can read comma-delimited files will access the string fields properly with or without the quotes. The only time a string field MUST be enclosed in quotes is when it contains an embedded comma. If Date fields are enclosed in pound signs , VB will automatically recognize the field as the Date data type.

If the Date fields are enclosed in quotes instead, you need to use the CDate function to convert the date from string format to the Date data type. In some sequential data files, fields are stored in a fixed position.

On each record, a particular field starts and ends in the same position and occupies the same amount of space. In a "print" format file, each line record of the file consists of a formatted "detail line" containing each field as if the lines were intended to be printed on a hard-copy report. In the example below, a column position guide is shown above the records.

From the example, it should be clear that the employee name occupies positions 1 through 20 of each record note that names shorter than 20 characters are padded with blank spaces ; the department number occupies positions 21 through 24; the job title occupies positions 30 through 50; the hire date occupies positions 51 through 60; and the hourly rate occupies positions 61 through Typical of sequential files originating on mainframe computers and processed by languages such as COBOL, fields are stored one after the other in a continuous string with no distinguishing marks or white space between them.

Although some of the character-string fields can be picked out easily, the numbers are run together and are difficult to interpret unless you know something about the record.

Also, numeric fields containing a decimal portion are typically stored without the decimal point they have an implied decimal point.

For example, the employee file might look something like this:. In the example above, the employee name occupies the first 20 positions of each record; the department number occupies the next four bytes note that it contains a leading zero ; the job title occupies the next 17 bytes; the hire date stored in MMDDYYYY format with no slashes occupies the next 10 bytes; and finally, the hourly rate occupies the last four bytes of the record.

Note that the hourly rate does not contain a physical decimal point; however, the program that processes this file must "know" that the decimal point is implied i. Given the proper data definition, COBOL can interpret the implied decimal point just fine; in VB, we have to convert the string "" to a number and then divide it by This technique is shown further below.

The Open statement prepares a file to be processed in the VB program. It identifies the Windows-system file that will be used in the program and assigns the file a file number that will be used to reference that file for the remainder of the program.

The general format is:. When a file is opened for Input, that file must already exist. When a file is opened for Output, if it does not exist, it will be created; if it does exist, its previous contents will be overwritten. When a file is opened for Append, if it does not exist, it will be created, if it does exist, records will be added to the file after the last record in the file the previous contents of the file will not be overwritten.

The Input and Line Input statements may only be used on files opened in the Input mode; the Write and Print may only be used on files open in the Output or Append modes. In order to avoid "hard-coding" the path of a file in your VB program, it is recommended that you use App. Path to reference the path of the file. This way, as long as the file resides in the same directory in which your program is running, the correct path will always be referenced. Path would refer to. So if you concatenate App.

Path with a backslash and the name of your data file, then you have a complete reference for your file, which can be used in the Open statement. The remaining major task is adding data to the end of a sequential file.

Execute the statement Dim sw As IO. AppendText filespec. After all the data have been recorded into the file, close the file with the statement sw. The IO. AppendText option is used to add data to an existing file. However, it also can be used to create a new file. If the file does not exist, then the IO. AppendText option creates the file. A file should not be open in two modes at the same time. For instance, after a file has been opened for output and data have been written to the file, the file should be closed before being opened for input.

For instance, had the statement sw. Close in Example 1 been omitted, then the program would have crashed when the second button was clicked. An attempt to open a nonexistent file for input terminates the program with a FileNotFoundException message box stating that the file could not be found.

There is a method that tells us whether a certain file already exists. If the value of. Therefore, prudence dictates that files be opened for input with code such as. Dim sr As IO. StreamReader If IO. There is one file-management operation that we have yet to discuss: changing or deleting an item of information from a sequential file. An individual item of a file cannot be changed or deleted directly. A new file must be created by reading each item from the original file and recording it, with the single item changed or deleted, into the new file.

The old file is then erased, and the new file renamed with the name of the original file. Regarding these last two tasks, the Visual Basic statement. Note: The IO. Delete and IO. Move methods cannot be used with open files; doing so generates an error message. Then, there is no need to insert the prefix "IO. The following program manages a file of names and years of birth:. Imports System. Handles btnAdd.

AppendText "YOB. TXT" sw. WriteLine txtName. Text sw. WriteLine mtxtYOB. Text [Page ] sw. Close txtName. Clear mtxtYOB. Clear txtName.

Handles btnLookUp. Exists "YOB. Handles btnDelete. OpenText "YOB. Text And sr. Clear Else MsgBox "Person is not in file. Clear End If sr. TXT" Do While sr. Text Then sw. WriteLine name sw. Close sw. Close File. Delete "YOB. TXT" File. Move "TEMP. Clear End If End Sub. Figure 8. Sample contents of YOB.

There are two main types of problems that a software program might encounter when it executes. The first is a bug , which is caused by incorrect or faulty code. Common examples of bugs are typos, using the wrong formula, and accessing the wrong property value. The second type is an exception , which, as the term suggests, is a situation that happens occasionally, but not all the time.

Two situations where exceptions occur are when invalid data are input and when a file cannot be accessed. The fundamental difference between bugs and exceptions is that bugs are totally caused by the programmer while exceptions are caused by events beyond the programmer's control. For example, if a user enters a word when the program prompts for a number, an exception is generated and the program terminates abruptly.

In this situation, the programmer did not employ faulty logic or mistype. If the user had followed the directions, no problem would have occurred. Even though the user is at fault, however, it is still the programmer's responsibility to anticipate exceptions and to include code to work around their occurrence. The Visual Studio environment contains powerful tools that programmers can use to find and correct bugs.

These debugging tools are discussed extensively in Appendix D. This section describes the techniques used to anticipate and deal with exceptions in programming terms, called "handling exceptions". An unexpected problem causes Visual Basic first to throw an exception and then to handle it. If the programmer does not explicitly include exception-handling code in the program, then Visual Basic handles an exception with a default handler.

This handler terminates execution, displays the exception's message in a window and highlights the line of code where the exception occurred. Consider a program that contains the following code:. Handles btnCompute. A user with no dependents might just leave the input dialog box blank and press the OK button. If so, Visual Basic terminates the program and displays the window shown in Figure 8.

The problem was caused by the fact that the default value in an input dialog box, the empty string, cannot be converted to an integer. Text boxes also have the empty string as their default value. It also highlights the fourth line of code since the exception was thrown while executing the CInt function. The program also would have crashed had the user typed in an answer like "TWO".

Exception handled by Visual Basic. A robust program explicitly handles the previous exception by protecting the code in a Try-Catch-Finally block. This allows the program to continue regardless of whether an exception was thrown. The computer tries to execute the code in the Try block.

As soon as an exception occurs, execution jumps to the code in the Catch block. Regardless of whether an exception occurred, the code in the Finally block is then executed.

The following code is illustrative:. We will assume your answer is zero. This type of exception handling is known as data validation. It catches situations where invalid data cannot be converted to a particular type. An exception is thrown if the user enters data that cannot be converted to an integer using the CInt function. Table 8. Some common exceptions. This item is displayed on page in the print version Exception Name. Any file handling exception, including those mentioned above.

For instance, an attempt is made to delete or rename an open file, to change the name of a closed file to an already used name, or when a disk drive specified contains no disk. Note: If a series of IO exceptions is being tested with Catch clauses, this exception should be the last one tested. This Catch block will be executed whenever any exception occurs. Visual Basic also allows Try-Catch-Finally blocks to have one or more specialized Catch clauses that only handle a specific type of exception.

The general form of a specialized Catch clause is. The code in this block will be executed only when the specified exception occurs.

The normal code is the code that you want to monitor for exceptions. If an exception occurs during execution of any of the statements in this section, Visual Basic transfers control to the code in one of the Catch blocks. As with a Select Case block, the Catch clauses are considered one at a time until the proper exception is located. The last Catch clause in the preceding code functions like the Case Else clause.

The clean-up code in the Finally block always executes last regardless of whether any exception-handling code has executed. In most situations, this code cleans up any resources such as files that were opened during the normal code.

If clean-up is not necessary, then the Finally statement and its corresponding code can be omitted. However, to complete a Try block, a Catch block or a Finally block must appear. In addition to data validation, a popular use of exception handling is to account for errors when accessing files. Visual Basic has the capability to access files stored on distant servers via the Internet. An exception is thrown if a desired file is missing IO.

FileNotFoundException or if the file cannot be read because the Internet connection between the computer and the server is broken IO. The following program reads the first line from a file on a diskette. The program expects the file to reside in the root directory of a floppy disk.

Note that the clean-up code, sr. Close , in the Finally block is enclosed in a Try-Catch block of its own. This protects the Close method from any exceptions that might occur.

Handles btnDisplay. Click Dim sr As IO. Sequential files make efficient use of disk space and are easy to create and use. Their disadvantages are as follows:. Often a large portion of the file must be read in order to find one specific item.

An individual item of the file cannot be changed or deleted easily. Another type of file, known as a database , has neither of the disadvantages of sequential files; however, databases use more disk space, and require greater effort to program.

Databases are discussed in Chapter Consider the sequential file shown at the end of Example 2. This file is said to consist of three records of two fields each.

A record holds all the data about a single individual. Each item of data is called a field. The three records are. Any variable declared within a Try-Catch-Finally block has block-level scope. That is, it will not be available after the block terminates.

TXT all repeated records except the first instance of a name matching the name in txtName. Assume that the existence of YOB. TXT is checked prior to the execution of this Sub procedure.

TXT only if the name to be added is not already present in the file. In Exercises 1 through 10, determine the output displayed in the text box when the button is clicked. WriteLine "Hello" sw. WriteLine "Aloha" sw. Close Dim sr As IO. ReadLine txtOutput. WriteLine "Bon Jour" [Page ] sw. AppendText file sw. WriteLine "Buenos Dias" sw. Text txtOutput. Substring 14, 1 txtOutput. Assume that the file AGES.

TXT is located in the Debug subfolder of the project folder bin and the first line of the file is "Twenty-one". ReadLine 'InvalidCast if fails txtOutput. FileNotFoundException txtOutput.

TXT contains an invalid age. TXT is not located in the Debug subfolder of the project folder bin. TXT are as shown in Figure 8. What is the effect of the following program? WriteLine g End If Loop sr. Assume that the contents of the file YOB. CreateText "YOB2. WriteLine "Clint" sw. WriteLine year Loop Do While sr. ReadLine sw. WriteLine End If sr.



0コメント

  • 1000 / 1000