vb6 reading writing text files

26
Search Level: Home › Tutorials How to read simple text files Written By TheVBProgramer . This tutorial describes how you can read text files in different formats and display them in your Visual Basic application. The samples here simply print the output to the main form, but this can easily be modified to do more advanced things with the text files. $ReqTestHarness$ Since this tutorial uses a framework to test all the code in and sample text files it is probably easier to first Download the source code for it than follow along with the tutorial. Visual Basic provides the capability of processing three types of files: sequential files - Files that must be read in the same order in which they were written – one after the other with no skipping around binary files - "unstructured" files which are read from or written to as series of bytes, where it is up to the programmer to specify the format of the file random files - files which support "direct access" by record number These three file types are "native" to Visual Basic and its predecessors (QBasic, GW-BASIC, etc.). 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: Open Prepares a file to be processed by the VB program. App.Path Supplies the path of your application FreeFile Supplies a file number that is not already in use Input # Reads fields from a comma-delimited sequential file Line Input # Reads a line (up to the carriage return) from a sequential file EOF Tests for end-of-file Write # Writes fields to a sequential file in comma-delimited format Print # Writes a formatted line of output to a sequential file Close # Closes a 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: Ads by Google VB6 Tutorials Function VB String Visual Basic 6 (VB6) How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files 1 of 26 2/9/2012 2:35 PM

Upload: nicksbruce

Post on 18-Apr-2015

383 views

Category:

Documents


17 download

TRANSCRIPT

Page 1: VB6 Reading Writing Text Files

Search

Level:

Home › Tutorials

How to read simple text files

Written By TheVBProgramer.

This tutorial describes how you can read text

files in different formats and display them in

your Visual Basic application. The samples here

simply print the output to the main form, but this can easily be

modified to do more advanced things with the text files.

$ReqTestHarness$

Since this tutorial uses a framework to test all the code in and

sample text files it is probably easier to first Download the

source code for it than follow along with the tutorial.

Visual Basic provides the capability of processing three types of

files:

sequential files - Files that must be read in the same order in which they were written – one after the other with

no skipping around

binary files - "unstructured" files which are read from or written to as series of bytes, where it is up to the

programmer to specify the format of the file

random files - files which support "direct access" by record number

These three file types are "native" to Visual Basic and its predecessors (QBasic, GW-BASIC, etc.). Thenext several topics address VB's sequential file processing capabilities. Binary and Random files will becovered in later topics.The following sequential file-related statements and functions will be discussed:

Open Prepares a file to be processed by the VB program.App.Path Supplies the path of your applicationFreeFile Supplies a file number that is not already in useInput # Reads fields from a comma-delimited sequential fileLine Input # Reads a line (up to the carriage return) from a sequential fileEOF Tests for end-of-fileWrite # Writes fields to a sequential file in comma-delimited formatPrint # Writes a formatted line of output to a sequential fileClose # Closes a file

As you know, a data file consists of records, which consist of fields. The file that will be used for allexamples in this section is a simplified employee file, which consists of the following fields:

Ads by Google VB6 Tutorials Function VB String

Visual Basic 6 (VB6)

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

1 of 26 2/9/2012 2:35 PM

Page 2: VB6 Reading Writing Text Files

Field Data Type

Employee Name String

Department Number IntegerJob Title StringHire Date DateHourly Rate Single

Suppose there were five records in the file. A graphic representation of the file populated with the fivedata records follows (the field names are not stored in the file):

Employee Name Dept # Job Title Hire Date Hourly Rate

ANDY ANDERSON 100 PROGRAMMER 3/4/1997 25.00

BILLY BABCOCK 110 SYSTEMS ANALYST 2/16/1996 33.50CHARLIE CHEESEMAN 100 COMPUTER OPERATOR 3/1/1996 15.00DARLENE DUNCAN 200 RECEPTIONIST 10/11/1998 12.75ERNIE EACHUS 300 MAIL ROOM CLERK 8/19/1997 10.00

Please note that the data types for these fields are the data types of the variables into which thesefields 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, ifyou opened up a sequential data file in a text editor such as Notepad, this is what you might see. Scenario 1: Comma-Delimited Format Each field is separated by a comma. Both string and numeric fields are "trimmed" (contain noextraneous spaces or zeroes). String fields are enclosed in quotes (Note: The quotes enclosing thestring fields are optional, VB and other applications that can read comma-delimited files will access thestring fields properly with or without the quotes. The only time a string field MUST be enclosed inquotes is when it contains an embedded comma.) If Date fields are enclosed in pound signs (#), VB willautomatically recognize the field as the Date data type. If the Date fields are enclosed in quotesinstead, you need to use the CDate function to convert the date from string format to the Date datatype.

"ANDY ANDERSON",100,"PROGRAMMER",#3/4/1997#,25

"BILLY BABCOCK",110,"SYSTEMS ANALYST",#2/16/1996#,33.5

"CHARLIE CHEESEMAN",100,"COMPUTER OPERATOR",#3/1/1996#,15

"DARLENE DUNCAN",200,"RECEPTIONIST",#10/11/1998#,12.75

"ERNIE EACHUS",300,"MAIL ROOM CLERK",#8/19/1997#,10

Scenario 2: Fixed-Width ("Print" Format) In some sequential data files, fields are stored in a fixed position. On each record, a particular fieldstarts 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 lineswere 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

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

2 of 26 2/9/2012 2:35 PM

Page 3: VB6 Reading Writing Text Files

should be clear that the employee name occupies positions 1 through 20 of each record (note thatnames shorter than 20 characters are padded with blank spaces); the department number occupiespositions 21 through 24; the job title occupies positions 30 through 50; the hire date occupies positions51 through 60; and the hourly rate occupies positions 61 through 65. 1 1 2 2 3 3 4 4 5 5 6 6

1...5....0....5....0....5...0....5....0....5....0....5....0....5.

ANDY ANDERSON 100 PROGRAMMER 3/4/1997 25.00

BILLY BABCOCK 110 SYSTEMS ANALYST 2/16/1996 33.50

CHARLIE CHEESEMAN 100 COMPUTER OPERATOR 3/1/1996 15.00

DARLENE DUNCAN 200 RECEPTIONIST 10/11/199812.75

ERNIE EACHUS 300 MAIL ROOM CLERK 8/19/1997 10.00

Scenario 3: Fixed-Width ("COBOL-Style" Format)

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:

1 1 2 2 3 3 4 4 5 5 6 6

1...5....0....5....0....5...0....5....0....5....0....5....0....5.

ANDY ANDERSON 0100PROGRAMMER 030419972500

BILLY BABCOCK 0110SYSTEMS ANALYST 021619963350

CHARLIE CHEESEMAN 0100COMPUTER OPERATOR030119961500

DARLENE DUNCAN 0200RECEPTIONIST 101119981275

ERNIE EACHUS 0300MAIL ROOM CLERK 081919971000

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.e., "2500" means "25.00"). Given the proper data definition, COBOL can interpret the

implied decimal point just fine; in VB, we have to convert the string "2500" to a number and then divide it by 100. This technique

is shown further below.

VB Statements and Functions for Sequential File Processing

The Open Statement

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 toreference that file for the remainder of the program. The general format is:Open <filename> [For mode] As [#] <filenumber>

· filename is a legal Windows-system filename, which may include a drive and path; thefilename can be specified in the Open statement as either a string constant or a string variable

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

3 of 26 2/9/2012 2:35 PM

Page 4: VB6 Reading Writing Text Files

· mode is one of the following three keywords: Input, Output, or Append.

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 previouscontents will be overwritten.

When a file is opened for Append, if it does not exist, it will be created, if it does exist, recordswill be added to the file after the last record in the file (the previous contents of the file will not beoverwritten).

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.

· filenumber is an integer from 1 to 511 which is used to associate the Windows-systemfilename with a number; this number will be used to reference the opened file in all further VBfile processing statements in the program.

Examples:

Open "C:\Program Files\EmpMaint\EMPLOYEE.DAT" For Input As #1

Open "A:\EMPLOYEE.DAT" For Input As #1

Using App.Path In order to avoid "hard-coding" the path of a file in your VB program, it is recommended that you useApp.Path to reference the path of the file. This way, as long as the file resides in the same directory inwhich your program is running, the correct path will always be referenced. For example, if both your program and the data file reside in C:\Program Files\EmpMaint, then that iswhat App.Path would refer to. So if you concatenate App.Path with a backslash and the name of yourdata file, then you have a complete reference for your file, which can be used in the Open statement. Examples:

Open App.Path & "\EMPLOYEE.DAT" For Input As #1

You could also use a string variable to hold the filename, as in the following example:

Dim strEmpFileName As String

strEmpFileName = App.Path & "\EMPLOYEE.DAT"

Open strEmpFileName For Input As #1

A special situation comes up if your program and the data file reside in the root directory of a drive (forexample A:\). If you concatenate App.Path with a backslash and the filename, you'll come up with aninvalid file reference, such as:

A:\\EMPLOYEE.DAT

To cover both situations and alleviate the pesky "extra backslash" problem, you can use code like thefollowing (the new statements are shown in bold):

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

4 of 26 2/9/2012 2:35 PM

Page 5: VB6 Reading Writing Text Files

Dim strEmpFileName As String

Dim strBackSlash As String

strBackSlash = IIf (Right$(App.Path, 1) = "\", "", "\")

strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT"

Open strEmpFileName For Input As #1

Using FreeFile

Instead of hard-coding the file number, you can use the VB function FreeFile to supply you with a file number that is not already

in use by the system. The FreeFile function takes no arguments and returns an integer. To use it, declare an integer variable,

then assign FreeFile to it, as follows:

Dim intEmpFileNbr As Integer

intEmpFileNbr = FreeFile

In the Open statement (and any other statement that refers to this file), use the integer variable ratherthan the hard-coded number. For example:

Open strEmpFileName For Input As #intEmpFileNbr

Thus, a "full-blown" procedure to open a sequential file for input might look like this: Dim strEmpFileName As String

Dim strBackSlash As String

Dim intEmpFileNbr As Integer

strBackSlash = IIf (Right$(App.Path, 1) = "\", "", "\")

strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT"

intEmpFileNbr = FreeFile

Open strEmpFileName For Input As #intEmpFileNbr

The Input # Statement

The Input # statement reads a series of fields (usually one "record's worth") from a comma-delimitedsequential file, and stores the contents of those fields into the specified variables. The general formatis: Input #<filenumber>, <variable list>

· filenumber refers to the file that was Opened As that number (for Input) in the Open

statement

· variable list is a list of variables, separated by commas, into which the data fields from the filewill be stored

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

5 of 26 2/9/2012 2:35 PM

Page 6: VB6 Reading Writing Text Files

Example:

Recall the comma-delimited version of the employee file shown earlier:

"ANDY ANDERSON",100, "PROGRAMMER",#3/4/1997#,25

"BILLY BABCOCK",110,"SYSTEMS ANALYST",#2/16/1996#,33.5

"CHARLIE CHEESEMAN",100,"COMPUTER OPERATOR",#3/1/1996#,15

"DARLENE DUNCAN",200,"RECEPTIONIST",#10/11/1998#,12.75

"ERNIE EACHUS",300,"MAIL ROOM CLERK",#8/19/1997#,10

Assume you declare the following variables in your program:

Dim strEmpName As String

Dim intDeptNbr As Integer

Dim strJobTitle As String

Dim dtmHireDate As Date

Dim sngHrlyRate As Single

the statement

Input #intEmpFileNbr, strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate

would cause ANDY ANDERSON to be stored in strEmpName, 100 to be stored in intDeptNbr, PROGRAMMER to be stored

in strJobTitle, 3/4/1997 to be stored in dtmHireDate, and 25 to be stored in sngHrlyRate the first time that the statement

was executed. The second time the statement was executed, BILLY BABCOCK, 110, SYSTEMS ANALYST, 2/16/1996, and

33.5 would be stored respectively in strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate; and so on. As VB

reads each field into its respective variable, it automatically performs the conversion to the correct data type (Integer, Date,

Single, etc.). As mentioned earlier, VB will only convert an incoming field to the Date data type if that field is enclosed in pound

signs (#) – if the field was enclosed in quotes, it would be treated as a string and the CDate function would have to be used

to convert it to a Date.

VB "knows" that the data is to be read from the "EMPLOYEE.DAT" file because the Input # statement isreferring to file #intEmpFileNbr, and file #intEmpFileNbr was associated with "EMPLOYEE.DAT" in theOpen statement. The EOF function

The operating system automatically appends a special character, called the end-of-file marker, to theend of a sequential file. VB can sense the presence of this end-of-file marker with the EOF function. A programming language will generally recognize EOF at either one of two times: (1) after the lastrecord has been read – OR – (2) at the same time that the last record has been read. COBOL fallsinto the first category, VB falls into the second. FYI: This discussion applies only to how VB processes sequential files – because when VB processesthe rows of a database table, it actually handles EOF "the COBOL way". In a language that recognizes EOF after the last record in the file has been read (such as COBOL), the"input" or "read" loop is set up similar like a prompted dialog loop: with a priming read outside the loop;all subsequent reads occur at the bottom of the loop. The pseudocode might be written as follows:

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

6 of 26 2/9/2012 2:35 PM

Page 7: VB6 Reading Writing Text Files

READ (first) RECORD

DO UNTIL EOF

PROCESS THE RECORD

READ (next) RECORD

LOOP

In a language that recognizes EOF when the last record is read (such as VB), the "input" or "read" loopmust be modified so that there is NO PRIMING READ and the read occurs as the FIRST statement inthe body of the processing loop. The pseudocode might be written as follows: DO UNTIL EOF

READ A RECORD

PROCESS THE RECORD

LOOP

The syntax of the EOF function is EOF(n) where n is a number corresponding to the file number of thefile from which you want to read data. n can either be a hard-coded number or an integer variable,depending on whether or not you used FreeFile in the Open statement. The EOF function can be used anywhere that a conditional expression can be used; as such, it mustalways follow keywords such as UNTIL, WHILE, and IF. The EOF function can also be preceded by thekeyword NOT: for example, Do Until EOF(1) is equivalent to Do While Not EOF(1). The main loop to process the employee file might look like this (note that there is no "priming" read andthat the input is done at the top of the loop):

Do Until EOF(intEmpFileNbr)

Input #intEmpFileNbr, strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate

' Processing for the record would go here – for example, load some of these

' fields into an element of an array or list box, print a line of a report, etc...

Loop

Building on what has been discussed thus far, the "full-blown" procedure to process a comma-delimited sequential file for input might look like this: Dim strEmpFileName As String

Dim strBackSlash As String

Dim intEmpFileNbr As Integer

Dim strEmpName As String

Dim intDeptNbr As Integer

Dim strJobTitle As String

Dim dtmHireDate As Date

Dim sngHrlyRate As Single

strBackSlash = IIf (Right$(App.Path, 1) = "\", "", "\")

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

7 of 26 2/9/2012 2:35 PM

Page 8: VB6 Reading Writing Text Files

strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT"

intEmpFileNbr = FreeFile

Open strEmpFileName For Input As #intEmpFileNbr

Do Until EOF(intEmpFileNbr)

Input #intEmpFileNbr, strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate

Print strEmpName; _

Tab(25); Format$(intDeptNbr, "@@@@"); _

Tab(35); strJobTitle; _

Tab(55); Format$(dtmHireDate, "mm/dd/yyyy"); _

Tab(70); Format$(Format$(sngHrlyRate, "Standard"), "@@@@@@@")

Loop

The Close statement When you are finished using a file in your program, you should Close that file. The Close statementtells VB that you are done using a file, and frees up the system resources needed to process that file. The statementClose #1

frees the resources used by the file referenced as #1, and also terminates the association between theWindows-system file and the file number – so at this point, if you wanted to, you could Open someother file AS #1. If you have more than one file open in a program, you can close multiple files with one Close statementby separating the file numbers with commas:Close #1, #2, #68

The statementClose

by itself on one line closes all files that are currently open. In the "full-blown" example above, the following line should be added to the end (after the "Loop"statement): Close #intEmpFileNbr

To demonstrate the code above

Create a new "Try It" project in a new folder. Make your form wide enough for the display.

In that same folder, create the comma-delimited file called EMPLOYEE.DAT (you can use NotePadfor this)

Place the code in the cmdTryIt_Click event procedure.

Run the program and click the "Try It" button. The output should look like this:

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

8 of 26 2/9/2012 2:35 PM

Page 9: VB6 Reading Writing Text Files

Download the VB project code for the example above here.

Similar linksCreating Advanced PDF documents in VB

Creating PDF files in Visual Basic

Save the contents of a list box to a file

Copy a File Quickly

Launch a program from VB

Get tag info form a mp3 file

Looping through files and putting them in a control

Delete A File - Snippet

PDF Writer for VB www.synactis.com

Create, display, print, edit, merge Royalty-freedistribution. Try now!

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

9 of 26 2/9/2012 2:35 PM

Page 10: VB6 Reading Writing Text Files

Documenting Your VB Code

What are databases and why do I care?

300391 reads

Tue, 01/24/2012 - 05:19 — Anonymous (not verified)

Thu, 12/29/2011 - 09:02 — Anonymous (not verified)

Sun, 12/18/2011 - 22:16 — tammy (not verified)

Fri, 12/09/2011 - 20:40 — Rainier (not verified)

Mon, 11/07/2011 - 23:28 — Anonymous (not verified)

Overflow

I have used the example as shown in the article, but I get the error code 6, overflow. I have no idea what that means or

how to solve it. HELP!

reply

GOOD

Thakssssssss

reply

Cannot access folder because the path is too long

Long Path Tool is very useful if you are having problems in deleting, unlocking, copying and even renaming files that are

considered filename too long by your system. Yes, these problems can occur even while using the latest Windows Explorer

or FAR in managing your files. This tool can help you simplify files names that are categorized as filename too long by your

system.

Lond Path Tool

reply

during read of a textfile.how to select a last row of a text?

pls teach me how to make a command during read of a textfile.how to select a last row of a text? and also it is possible to

have a automatic show of text in textbox.example i use barcode to another vb application then after barcode make a

serial number in another vb application.it is possible that my vb application the serial number appear in another vb

application also appear in my textbox???

reply

How to read first and last word in textbox

Public Function GetFirstWord(ScanString As String) As String

Dim intPos As String

Dim intPosSave As String

If InStr(ScanString, " ") = 0 Then

GetFirstWord = ""

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

10 of 26 2/9/2012 2:35 PM

Page 11: VB6 Reading Writing Text Files

Sun, 09/25/2011 - 10:38 — Anonymous (not verified)

Exit Function

End If

intPos = 1

intPos = InStr(intPos, ScanString, " ")

GetFirstWord = Trim$(Left$(ScanString, intPos))

End Function

Public Function GetLastWord(ScanString As String) As String

Dim intPos As String

Dim intPosSave As String

If InStr(ScanString, " ") = 0 Then

GetFirstWord = ""

Exit Function

End If

intPos = 1

Do

intPos = InStr(intPos, ScanString, " ")

If intPos = 0 Then

Exit Do

Else

intPos = intPos + 1

intPosSave = intPos + 1

End If

Loop

GetFirstWord = Trim$(Mid$(ScanString, intPosSave + 1))

End Function

reply

login page

Hi,

I am signing into my system either as a doctor or a nurse. How would i show that I have sign in as a doctor/nurse in the

new form I entered.

I have already created a label to display the doctor/nurse. Anyway I am using a combo box in my login form for the

option if doctor and nurse. Once logged in I cant retrieve the combo box text to my new form. Below are my codes.

Adodc1.RecordSource = "Select * from login where username = '" + Text1.Text + "'"

Adodc1.Refresh

If (Adodc1.Recordset.EOF = False) Then

If (Text2.Text = Adodc1.Recordset.Fields("password") And Combo1.Text = Adodc1.Recordset.Fields("Class")) Then

MsgBox "login Success"

Unload Me

MDIClinic.Show

MDIClinic.mnInvoice.Enabled = True

MDIClinic.mnConsultation_Treatment.Enabled = True

MDIClinic.mnPatient_Information.Enabled = True

MDIClinic.mnPatient_Registration.Enabled = True

MDIClinic.InvoiceButton.Enabled = True

MDIClinic.SSTab1.Enabled = True

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

11 of 26 2/9/2012 2:35 PM

Page 12: VB6 Reading Writing Text Files

Sat, 03/19/2011 - 07:35 — Marie Albaugh (not verified)

MDIClinic.Label14.Caption = Combo1.Text < this is the line >tried debugging it

Else

MsgBox "invalid password"

Text1.Text = ""

Text2.Text = ""

Text1.SetFocus

End If

Else

MsgBox "invalid username"

Text1.Text = ""

Text2.Text = ""

Text1.SetFocus

End If

reply

functions and reading data

Hello I was given this project to do over spring break. I don't know if I have read the data wrong or if my function is

wrong can't seem to get the data to show up or the calculation to work. here what I am to do.

The data file is name P06.DAT, contains a Sales Person Name and a Sales amount in each of its data lines for every Sales

Person of a company. Each data line has two data items as describe below:

Items # Description Data Type

1 salesperson name String (maximum length 16)

2 Sales Amount Floating-point

A salesperson is assigned commission on the flowing basis:

SALE AMOUNT COMMISSION

Less than $100 0.00 %

$100 to $999.99 2.85%

$1000 to $4999.99 4.75%

$5000 to $100000 6.95%

Over $10000 9.75%

At the top of your code you must provide a project name and Author Name

The Main() in the Module P06 will perform the as follows:

1. At the top of the output screen display Your name and Assignment #

2. Print Company Name and Column Headings.

3. Read each data line.

4. You use a Function to calculate Commission Amount, rounded to decimal places.

5. Compute running totals for Sales Amount, and Commission Amount.

6. Print Sales Person Name, Sales Amount, and Commission Amount under the heading.

7. At the bottom of the output print Total Sales Amount and Total Commission.

that is the assignment having trouble with the function I don't know if I have that wrong or the way I read and open the

data file. Here is a copy of my program that I have so far wasn't sure how to round off to the 2 decimal and the floating-

point I just am not good in the math area and how to do calculation. Any input would be grateful thanks.

'----------------------------------------------------------------------------'

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

12 of 26 2/9/2012 2:35 PM

Page 13: VB6 Reading Writing Text Files

' Project: P06VB '

' Author: Marie Albaugh '

'----------------------------------------------------------------------------'

Imports System.IO

Imports RahimLibrary

Module P06

Const AUTHOR As String = "Marie Albaugh Assignment 6"

Const HEAD1 As String = "MARIE ALBAUGH'S HEART OF GOLD"

Const HEAD2 As String = _

"SALESPERSON_NAME SALES_AMT COMMISSION"

Const LINE = _

"-------------------------------------------"

Const FMT As String = "0.00"

'-------------------- Subroutine: Main() -------------------------------------

Sub Main()

Dim Tokens As StringTokenizer

Dim Diskfile As String = "P06.DAT"

Dim separator As Char() = {" ", ",", ";", ":"}

Dim gap As Integer

Dim Name As String

Dim commission, totalSalesAmt, totalCommission, salesAmt As Decimal

totalSalesAmt = 0

totalCommission = 0

Console.WriteLine(AUTHOR & vbNewLine)

gap = (80 - HEAD1.Length) \ 2

Console.WriteLine(Space(gap) & HEAD1)

gap = (80 - HEAD2.Length) \ 2

Console.WriteLine(Space(gap) & HEAD2 & vbNewLine & Space(gap) & LINE)

If Not File.Exists(Diskfile) Then

Console.WriteLine("File: " & Diskfile & " does not exist")

Console.WriteLine(vbNewLine & vbNewLine)

Exit Sub

End If

FileOpen(1, Diskfile, OpenMode.Input)

While Not EOF(1)

Tokens = New StringTokenizer(LineInput(1), separator)

Name = Tokens.NextToken() & " " & Tokens.NextToken()

Name = Name & Space(16 - Name.Length)

salesAmt = Tokens.NextToken()

commission = Tokens.NextToken()

salesAmt = Tokens.NextToken()

commission = calculateCommission(salesAmt, commission)

totalSalesAmt = totalSalesAmt + salesAmt

totalCommission = totalCommission + commission

commission = salesAmt * commission

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

13 of 26 2/9/2012 2:35 PM

Page 14: VB6 Reading Writing Text Files

Console.WriteLine(Space(gap + 1) & Name _

& Format(Name, FMT).PadLeft(13) _

& Format(salesAmt, FMT).PadLeft(12) _

& Format(commission, FMT).PadLeft(13))

End While

FileClose(1)

totalCommission = salesAmt * commission

Console.WriteLine(Space(gap) & LINE & vbCrLf _

& Space(gap + 1) & "TOTALS:" _

& Format(totalSalesAmt, FMT).PadLeft(12) _

& Format(totalCommission, FMT).PadLeft(16) _

& vbCrLf & Space(gap) & LINE & vbCrLf & vbCrLf)

End Sub

'-------------------- Function: calculateCommission() -----------------------------

Function calculateCommission(ByVal salesAmt As Decimal, _

ByVal commission As Decimal) As Decimal

If (salesAmt > 100000) Then

commission = salesAmt * 9.55

ElseIf (salesAmt >= 5000) Then

commission = salesAmt * 6.95

ElseIf (salesAmt >= 1000) Then

commission = salesAmt * 4.75

ElseIf (salesAmt >= 100) Then

commission = salesAmt * 2.85

Else

commission = 0.0

End If

commission = Utility.Round(commission, 2)

'commission = Math.Round(commission,2)

'commission = Math.Floor(salesAmt * commission)

Return commission

End Function

End Module 'P06

The data file is this

Harry Hacker 75.79

Carl Cracker 99.99

Tony Teaser 100.00

Susan Shake 885.79

Barbara Bake 999.99

Carol Cook 1000.00

Shirley Stew 4575.79

Simple Pimple 4999.99

Horrible Huey 5000.00

Felix Laketrout 5759.53

Rickety Pork 10000.00

Peter Popcorn 10000.01

Quickdraw McGraw 12537.87

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

14 of 26 2/9/2012 2:35 PM

Page 15: VB6 Reading Writing Text Files

Mon, 03/07/2011 - 10:51 — at andy (not verified)

Sun, 02/27/2011 - 11:20 — CantEditman (not verified)

Thanks for your time

reply

how to open text file with half of its name

Hi.

Can you help me,..?

How to open text file with half of its name using vb6. example i have 2 files in C:\,

they are :

1. Myfile10001.txt

2. Myfile20001.txt

I want to read file no.2 with 7 characters first (Myfile2xxxx.txt), and ignore next characters.

my script is :

Option Explicit

dim file1, file2, astrx

astrx = "*"

file1 ="c:\Myfile10001.txt"

file2 ="c:\Myfile2" & astrx & ".txt"

'this is run

Sub OpenTextFile1

Const ForReading = 1, ForWriting = 2, ForAppending = 3

Dim fs1, f1

Set fs1 = CreateObject("Scripting.FileSystemObject")

Set f1 = fs1.OpenTextFile(file1, ForReading,TristateFalse)

f1.Close

End Sub

'this is error

Sub OpenTextFile2

Const ForReading = 1, ForWriting = 2, ForAppending = 3

Dim fs2, f2

Set fs2 = CreateObject("Scripting.FileSystemObject")

Set f2 = fs2.OpenTextFile(file2, ForReading,TristateFalse)

f2.Close

End Sub

reply

How to edit and arrange words in a text file?

Hi,

Can you please help me for this one, i'm confused on how to start my program. It's more like of a combination.

Here is what the original text file looks like:

"John dela Torre","14","Freshman","Math","English","Science","History","PE","C:\Johndelatorre.jpeg"

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

15 of 26 2/9/2012 2:35 PM

Page 16: VB6 Reading Writing Text Files

Sun, 02/27/2011 - 10:31 — tonywest (not verified)

Wed, 01/26/2011 - 04:51 — Anudeep (not verified)

Fri, 01/28/2011 - 10:28 — TMowers (not verified)

"Susan Green","13","Freshman","Math","English","Science","History","Home Economics","C:\Susangreen.jpeg"

And this is what the output should be

John dela Torre 14 Freshman Math

English

Science

History

PE C:\Johndelatorre.jpeg"

Im so confused with the split function and searching for the solution for rearranging this. Please help. T__T

reply

Many Thanks

I would just like to say thank you to whoever writes these tutorials. I have made several attempts to learn VB but always

seemed to get stuck trying to get my head around some of the context of the commands. I have read through all the

tutorials so far and everything makes perfect sense now. As soon as I have read through them all I will go back and try

the code with the confidence that I have some kind of idea as to what I am doing.

Great Work!!!!!

Many Thanks (again)

Tony

reply

Excellent Tutorial..

How can I read from the middle(any place rather than the starting position) of a line in vb.

reply

Use the Mid Function

To read from anyplace in your line, use the MID function. You have to know where you are starting (or you can use

the INSTR function for this). Examples of both are shown below.

Dim intPosition as integer

Dim myString as string

Dim myOutput as string

myString = "Mary had a little lamb"

intPosition = instr(1,myString, "little") 'the 1 simply tells it from which character in the string (myString) to start

looking.

myOutput = mid(myString, intPosition,6) ' this should return the word 'little'.

reply

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

16 of 26 2/9/2012 2:35 PM

Page 17: VB6 Reading Writing Text Files

Sun, 01/16/2011 - 12:11 — Muzammal Baig (not verified)

Tue, 11/02/2010 - 07:33 — Nishant Pawar (not verified)

Sat, 08/28/2010 - 00:06 — balachandar (not verified)

Thu, 07/22/2010 - 01:03 — nosebleed (not verified)

Sun, 01/16/2011 - 12:18 — Muzammal Baig (not verified)

Alternative to APP.PATH

Its work done very well.

Just want to add the alternative way to APP.PATH

Instead of using (APP.PATH & "\") you can use ".\" it will always point to current working directory of VB6. i.e. the

APP.PATH.

This method automatically gets rid of the double "\" problem.

You can also use "..\" to point to the parent directory of your APP.PATH.

Or ".\subdirectory" to point to a sub directory or sub-sub directory of App.Path

reply

Superb.!!!!!!!!!

Really nice tutorial for beginners...!!!!!

reply

how to open msoffice using vb

sir ,vb6.0 using sourcecode how to open msword,msexcel,notepad&msaccess in a single form to split the application

display on single form

reply

getting data to notepad

data received : 09276578797 8mins

data received : 09256578797 3mins

data received : 09276578797 8mins

i want to get all the number of 0927 to total the mins....

so the total minutes of 0927 is 16mins....

how can i make of this project... T_T

help me....

reply

instr() is much better than using mid()

use instr(start,string_name_to_be_searched,string to find) and the full phone number can be found as many times as

you like

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

17 of 26 2/9/2012 2:35 PM

Page 18: VB6 Reading Writing Text Files

Mon, 08/09/2010 - 22:57 — au_simple (not verified)

Mon, 08/09/2010 - 22:56 — au_simple (not verified)

Tue, 07/06/2010 - 04:20 — RENJINI (not verified)

Thu, 04/15/2010 - 15:01 — Daniyal (not verified)

also instr() will find " " for you so that you know where is the minutes info

reply

getting data to notepad

do you have these data int he notepad or somewhere else on the form (like listbox)? either way, if you know how to

read each entries int he notepad or list, you can use mid() function to see if the value is 0927 then use same mid()

function to get the number of minutes and add it.

reply

do you have these data int

do you have these data int he notepad or somewhere else on the form (like listbox)? either way, if you know how to

read each entries int he notepad or list, you can use mid() function to see if the value is 0927 then use same mid()

function to get the number of minutes and add it.

reply

thankyou

thankyou

reply

conversion

I want to know how can i convert the result of a program i made in gw basic in text form.

10 CLS

20 PRINT TAB(20) "list of names"

30 PRINT

35 A=0

40 PRINT TAB(20) "names"

50 PRINT

60 INPUT "enter your name|-",N$

65 PRINT LEFT$(N$,1),

70 A=A+1

80 IF LEFT$(N$,1)="z" THEN PRINT "end of the list":GOTO 130

90 GOTO 50

130 END

plz help me.....

reply

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

18 of 26 2/9/2012 2:35 PM

Page 19: VB6 Reading Writing Text Files

Wed, 03/03/2010 - 05:46 — Evan Millana (not verified)

Mon, 02/08/2010 - 20:22 — enzo (not verified)

Tue, 01/26/2010 - 22:53 — pawarvirendra

So Cool ! Tut but how to

So Cool ! Tut

but how to make it "print" in textbox or listbox instead on a form

Please help me !

reply

Random Access of Text Documents

hi! where can i find the tutorial for random access of files?

thanks...

reply

Cant write above 255 char in text File

Dim strFile As String

Dim strBackSlash As String

Dim strTextFileName As String

Dim strCurrentChar As String * 1

Dim intTextFileNbr As Integer

Dim lngX As Long

Dim rString As String

Dim wString As String

Private Sub writeFile(strFile As String)

strFile = "MA.txt"

strBackSlash = IIf(Right$(App.Path, 1) = "\", "", "\")

'strTextFileName = App.Path & strBackSlash & "Test.txt"

strTextFileName = App.Path & strBackSlash & strFile

If Dir$(strTextFileName) <> "" Then

Kill strTextFileName

End If

' Open Output File

intTextFileNbr = FreeFile

Open strTextFileName For Binary Access Write As #intTextFileNbr

'For lngX = 1 To Len(wString)

For lngX = 1 To 255

strCurrentChar = Mid$(wString, lngX, 1)

Put #intTextFileNbr, , strCurrentChar

Next

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

19 of 26 2/9/2012 2:35 PM

Page 20: VB6 Reading Writing Text Files

Thu, 01/21/2010 - 09:48 — Rahul Gandhi (not verified)

Thu, 12/03/2009 - 17:12 — Anonymous (not verified)

Tue, 11/24/2009 - 13:47 — ه�� ��وژ� �� دا� (not verified)

txtTemp.Text = Len(wString)

Close #intTextFileNbr

a:

End Sub

reply

wow

what an explanation to the code... Great man! Tons of thanks!

reply

THANKS

THANKS

reply

ه�� ��وژ� دا���د�� دا�

��و� 5 در ش��� � ارا�� ��� وب ا� در �� ه� ��وژ� ���: �ش$� � ذ" ش�ح � �

��ر&%�$ ه�� ��وژ�

وب )'� ه�� ��وژ�

ه�� ��وژ� -2-1 ASP.NET ( *(�� وب�� Dynamic)

ه�� ��وژ� -2-2 HTML ( *(�� وب�� Static)

داد� ��+�� ه�� ��وژ�

SQL Server ��وژ� -3-1

Access ��وژ� -3-2

, ����� ه�� ��وژ���

4-1- ����� ,ش�رپ � ز �ن � �� (C#)

4-2- ����� ,�� دات 23,3 و1وال ز �ن � �� (VB.NET)

4-3- ����� ,6.0 23,3 و1وال ز �ن � �� (Visual Basic 6.0)

4-4- ����� ,��ش�3 ز �ن �� (Assembly)

4-5- ����� ,ز �ن � �� C و C++

ا%5ار ��م �($�� و �3,*�(� )'�3" و )�5� ه�� ��وژ�

5-1- �روش � �3,*�(� )'�3" و )�5 UML (�*� RUP � ا���ا%5ار ��م � ���دار ر�8 ه Rational Rose و . . . )

5-2- �روش � �3,*�(� )'�3" و )�5 SSADM ( و ��ا ش )'�3" روش . . .)

��ا%93 ه�� ��وژ�

ه�� ��وژ� -6-1 Multi Media Builder

ه�� ��وژ� -6-2 Flash MX

�ن از ���*� 24 � *3>�� � )��$�ن �� ا�� �;*:� 3*���%��* �ن ر<�� ز�د� ح�ود )� )�ا�,*� ��* � ج�? را ����ن 3 *� ر<�� ج�? �ا� و را�*� ه��3 در. ��* �ا� و �

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

20 of 26 2/9/2012 2:35 PM

Page 21: VB6 Reading Writing Text Files

Mon, 11/02/2009 - 23:39 — Kiran KK (not verified)

Fri, 10/09/2009 - 20:08 — Anonymous (not verified)

Thu, 07/02/2009 - 08:48 — sage334

Fri, 06/12/2009 - 03:29 — Anonymous (not verified)

Mon, 05/04/2009 - 22:49 — shekar (not verified)

2 ا��د � ا�Aام �$��>*� ���:+� ��ا�� (Forum) د����ن �� ��� �ن و دا��* ��م ا�ادات ر%F و &��زش خ�ا�� در ، خ�� از A>" ��اCت �B ا� از )�ا�$� � �'*�م �

$� ��Gح ا���� ا� در خ�� از �B را خ�د ا%5ار���ش� خ�اه� داد� ���K &�(� ��اCت � � *��<3 �J,�ل )��I و�A ا��ع در �� � .

����ن ال>*�� 3>��* M از ��N س���3" ار��ل � و )�;$ )� و ا F%ر� اش�9ل ر�Pت � ه� ��وژ� ا���م �'" در ح�A د�خ A� �$اه�خ ���� .

�3$Q��ن ه�* �ن و ��� ���� R�رت � �,:� 2 ، ��ج�د ه�� ��وژ� خ�� از A>" )�ا�$� � �'*�م دا�� � Demo ه�� را ��وژ� از� � �$��A>�ل ��رد ��وژ� �� R�ر) در و �

FAار� را &ن ، ش� وا�$� خ���� .

���دارا� ال��T %�ق ه�� ��وژ� ) Document ، �,*$�ات و 3>��* � B� زش و %�وش از�ح� در &� ��ار� ��وژ� از ا�*;�د� و اج�ا �'�R�ر) در. �ش� � ��را�* و ش�� خ�

3 *�� اUN��ت � �� ���س �� � ��3ز�$�( "R�3 ح�����% .

reply

This is code is really

This is code is really helped me a lot to do my project...

Thank s...

reply

Writing or editing textline

Hello, nice tutorial. Very useful

Can you also post writing or editing textline.

Thx in advance.

jterc

reply

I like it

Graet lesson, very helpfull

Tanks

reply

how do u get the app path to

how do u get the app path to work

reply

wow..This is just amazing

wow..This is just amazing site and just wonderfukl article.

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

21 of 26 2/9/2012 2:35 PM

Page 22: VB6 Reading Writing Text Files

Wed, 03/25/2009 - 17:30 — Alaa Noor (not verified)

Wed, 02/04/2009 - 11:17 — Ranjith Kumar (not verified)

Thu, 01/29/2009 - 09:15 — Anonymous (not verified)

Thu, 12/18/2008 - 23:39 — aruna

Wed, 11/19/2008 - 15:36 — mikaeel.ghany

Mon, 11/10/2008 - 10:54 — Anonymous (not verified)

This is the best explanation one could ever give.u rcok man..

reply

Thank you !

Very Nice explaination , much better than what i read in many books

thanks a lot sir

reply

Wonderful Tutorial, just what we needed

Wonderful Tutorial, just what we needed..thxs

reply

Great

Well done

reply

how up load text files

how up load text files to sql server database by using vb6

reply

how to open using a box like windows explorer

how do i allow the user to choose the file to open by using a open box like the one windows uses with windows explorer,

e.g. in MS Word or Paint. I really need help!!!!!

reply

Great tutorial =) it help me

Great tutorial =)

it help me so much tks [[]]

reply

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

22 of 26 2/9/2012 2:35 PM

Page 23: VB6 Reading Writing Text Files

Sat, 10/25/2008 - 21:33 — LazyPrinzez (not verified)

Sat, 10/25/2008 - 21:33 — LazyPrinzez (not verified)

Sun, 09/28/2008 - 01:28 — Anonymous (not verified)

Sat, 09/27/2008 - 19:13 — Anonymous (not verified)

Wed, 02/11/2009 - 20:58 — Anonymous (not verified)

Tue, 09/02/2008 - 12:44 — Adnan (not verified)

Very Nice Tutorial

One thing I really needed for our TLE Project.

I'm just a 15-year-old senior high school student and our teacher introduced VB6.0 to us and gave us so many activities

and assignments that I can't catch up with the deadlines--I guess it's just too much for our age (but I think it's fun though,

TLE is actually one of my favorite subjects)--so I sorely needed a tutorial for it.

Thank you so much! You don't know how much this helps me with our TLE projects and activities!

reply

Very Nice Tutorial

One thing I really needed for our TLE Project.

I'm just a 15-year-old senior high school student and our teacher introduced VB6.0 to us and gave us so many activities

and assignments that I can't catch up with the deadlines--I guess it's just too much for our age (but I think it's fun though,

TLE is actually one of my favorite subjects)--so I sorely needed a tutorial for it.

Thank you so much! You don't know how much this helps me with our TLE projects and activities!

reply

COOL

i always had problem with opening apps. at least now i can clearly open text or apps. tnx again

reply

EXPORTING

CAN YOU TELL ME HOW TO EXPORT .FRM TO .EXE

reply

Open the file in vb6 and go

Open the file in vb6 and go under file to export as project name.exe

reply

Thanks

THANK YOU SO MUCH !!!

It is an outstanding effort from ur side, It was so helful for me.

God Bless U !!!!

reply

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

23 of 26 2/9/2012 2:35 PM

Page 24: VB6 Reading Writing Text Files

Sat, 05/24/2008 - 10:18 — Anonymous (not verified)

Sun, 03/09/2008 - 22:20 — Anonymous

Mon, 01/14/2008 - 09:17 — Anonymous

Fri, 11/16/2007 - 23:09 — Anonymous

Wed, 08/29/2007 - 11:13 — Anonymous

If I only want to get a few

If I only want to get a few data from the text (not the whole text), how can I do it?

reply

Quite helpfull but it does

Quite helpfull

but it does not show how to wirte into file

reply

congrats, very good

congrats, very good 1

Márcio

reply

vb6 textboxcontrol

can u tell me how can i bold or change the color of the selected text in the text box like in MS Word.

reply

Wonderful Tutorial, just what we needed

Also, to read the text file line by line:

nHandle = FreeFile

Open "logfile.txt" For Input Access Read As #nHandle

Do While Not EOF(nHandle) '// Loop until end of file.

Line Input #nHandle, TextLine '// Read line into variable.

' use the TextLine herer...

Loop

Close #nHandle

reply

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

24 of 26 2/9/2012 2:35 PM

Page 25: VB6 Reading Writing Text Files

Tue, 08/28/2007 - 23:30 — Anonymous

Tue, 07/17/2007 - 18:03 — Anonymous

Sat, 06/09/2007 - 21:28 — Anonymous

Sun, 06/03/2007 - 15:34 — Anonymous

Sat, 12/15/2007 - 09:50 — ClaweD

Mon, 03/10/2008 - 15:37 — Anonymous

Excellent Tutorial

A great piece of tutorial. Step by step and in a very simple way.

Keep it Up

Sameer

[email protected]

reply

Exporting files

can you tell me ow to export files? for example, I created a loop that will record all the data into a variable. how can I

export all the data in the variable into a text file?????

reply

great

very very helpful

reply

Scenario 2: Fixed-Width ("Print" Format)

i would like a tutorial that discribes how to read a text file with that format.

thanks, its a great tutorial.

reply

ClaweD`s Answers :D

nice job :D

gonna post my own tutorials soon when i figure out how ^^

reply

Great Wrok

I love this site,

great work

Thanks, very helpfull

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

25 of 26 2/9/2012 2:35 PM

Page 26: VB6 Reading Writing Text Files

Unless otherwise noted, all content on this site and in the source samples is Copyrighted © 2011 by the owner of vb6.us.

All rights reserved - Contact Information

reply

Post new comment

Your name:

Anonymous

E-mail:

The content of this field is kept private and will not be shown publicly.

Homepage:

Subject:

Comment: *

Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>

Lines and paragraphs break automatically.

More information about formatting options

Preview

How to read simple text files | Visual Basic 6 (VB6) http://www.vb6.us/tutorials/how-read-simple-text-files

26 of 26 2/9/2012 2:35 PM