How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
Visual Vi sual Basic 6 (VB6) (VB6 )
Search
Home › Tutorials
How to read simple text files Written By TheVBProgramer TheVBProgramer.. Level: This tutorial describes how how you can read tex t files in different formats and display them in your Visual Basic application. application. The samples sam ples here simply print the output to the main form, but this can can easily be modified to do m ore advanced things with the text files. $ReqTestHarness$ Since this tutorial tutorial uses a framewo rk 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: - Files that must be read in the same order in which they were written – one after the other with no skipping around sequential files
- "unstructured" "unstructured" files which are read re ad from or written to as series of byte s, where it i t is up to the programmer to specify the format of the file
binary files
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 several topics address VB's sequential file processi p rocessing ng capabilities. Binary and Random files will be covered in later topics. The following sequential file-related statements and functions will be discussed: Open App.Path FreeFile Input # Line Input # EOF Write # Print # Close #
Prepares a file to be process pr ocessed ed by the VB program. Supplies the path of your application Supplies a file number that is not already in use Reads fields from a comma-delimited sequential file Reads a line (up to the th e carriage carriage return) from a sequential file fil e Tests for end-of-file Writes fields to a sequential sequ ential file in comma-delimited comma-delimited format Writes a formatted line of output to t o a sequential file Closes a file
As you you know, a data file consists of records, which consist of fields. The file that will be used for all examples examples in this t his section is a simplified employee file, which consists of the following field s:
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
Field Employee Name
Data Type String
Department Number Job Title Hire Date Hourly Rate
Integer String Date Single
Suppose there were five records records in the th e file. A graphic representation representation of the th e file populated popul ated with the five data records follows (the field names are not stored in the file): fil e): Employee Name
Dept #
Job Title
Hire Date
ANDY ANDERSON BILLY BABCOCK CHARLIE CHEESEMAN DARLENE DUNCAN ERNIE EACHUS
100 110 100 200 300
PROGRAMMER SYSTEMS ANALYST COMPUTER OPERATOR RECEPTIONIST MAIL ROOM CLERK
3/4/1997 2/16/1996 3/1/1996 10/11/1998 8/19/1997
Hourly Rate 25.00
33.50 15.00 12.75 10.00
Please note that the data types for these fields are the data types of the th e variables 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, example, if you 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 no extraneous extraneous spaces or zeroes). zeroes). String fields are enclosed in quotes (Note: The quotes enclosing th e string fields are optional, optional, VB and other applications that can read comma-delimited comma-delimited files will access the string fields properly with or without the th e quotes. The only time a string field MUST MUST be enclosed in quotes is when it contains an embedded comma.) If Date fields are enclosed in pound sign s (#), VB will automatically automatically recognize the field as the th e Date data type. If the Date fields are enclosed in quotes qu otes instead, you need to use the CDate function to convert the date from string format to the th e Date data type. "ANDY ANDERSON",100,"P ANDERSON",100,"PROGRAMMER",#3/ ROGRAMMER",#3/4/1997#,25 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 sequential data d ata files, fields are stored in a fixed position. position. On each record, a particular field starts and ends in the same position position and occupies the th e same amount amount of space. In a "print" "print " format file, each line (record) of the file consists of a formatted "detail line" l ine" containing each field (as if the th e lines were intended to be printed on a hard-copy h ard-copy report). In the example below, below, a column position guide is shown above above the records. From the t he example, example, it
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
should be clear that the employee empl oyee name name occupies positions positions 1 through throug h 20 of each record record (note that names shorter than 20 characters characters are padded with blank bl ank spaces); the department number occupies positions 21 through 24; the job title t itle occupies positions positions 30 through 50; the hire date occupies positions positions 51 through 60; and the t he 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 ("COB ( "COBOL-Style" OL-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 t o be processed in the th e VB program. It identifies the Windowssystem 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 th e remainder of the program. The general g eneral format is: Open
[For mode ] As [#]
·
filename is
a legal Windows-syste Wind ows-system m filename, which may include a drive d rive and and path; the filename can be specified in the Open statement as either a string constant or a string variable variable
How to read simple text files | Vi Visual Basic 6 (VB6)
·
mode is
http://www.vb6.us/tutorials/how-read-simple-text-files
one of the following f ollowing three keywords: Input, Output, or Append.
When a file is opened for Input, Inpu t, that file must already exist. When a file is opened for Output, Ou tput, if it does not exist, it will be b e created; created; if it does exist, exist, its previous previous contents will be overwritten. overwritten. When a file is opened for Append, if it does not exist, it will be created, if it does d oes exist, 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 statements may only be used on files fil es 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-system filename with a number; this number will be used to reference the opened file in all further VB file 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 avoid "hard-coding" the path of a file fil e in your VB program, it is recommended that you use App.Path to reference the path of the file. fil e. This way, way, as long l ong as the file resides in the th e same directory in which your program is running, run ning, the t he correct path will always be referenced. For example, example, if both b oth your program and the t he data file reside in C:\Program C:\Program Files\EmpMaint, then that is what App.Path would refer to. So if you concatenate App.Path App.Path with a backslash and the name n ame of your data file, then you have a complete complete reference for 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 u se a string variable variable to hold the filename, as in the foll owing example: example: Dim strEmpFileName As String strEmpFileName = App.Path & "\EMPLOYEE.DAT" Open strEmpFileName For Input As #1
A special special situation situ ation comes up if your program and the th e data file reside in the root directory of a drive (for example A:\ ). ). If you concatenate App.Path App.Path with a backslash and the filename, fil ename, you'll come up with an invalid file reference, such as: A:\\EMPLOYEE.DAT
To cover cover both situations and alleviate alleviate the pesky "ex " extra tra backslash" problem, p roblem, you can use u se code like the following (the (th e new statements statements are shown in bold): bold ):
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-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 th e integer variable variable rather than the th e hard-coded number numb er.. 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 Statement
The Input # stateme st atement nt reads a series of fields (usually one "record's worth") from a comma-delimited sequential file, and stores the contents of those th ose fields into the th e specified variables. variables. The general format is: Input #, #,
· ·
filenumber refers to the file that was Opened As that
number (for Input) in the Open
statement variable list
will be stored
is a list of variables, separated separated by commas, into which the th e data fields from the file fil e
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
Example: Recall the comma-delimited version of the employee file shown earlier: "ANDY ANDERSON",100, ANDERSON",100, "PROGRAMMER",#3/4/1997#,25 "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 SYSTEM S ANALYST ANALYST , 2/16/1996, and was executed. The second time the statement was executed, BILLY BABCOCK, 110, SYSTEMS 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 convert it to a Date.
VB "knows" that the data is to be read from the "EMPLOYEE.DAT" file because the Input # statement is referring to file f ile #intEmpFileNbr, and file f ile #intEmpFileNbr was associated associated with "EMPLOYEE.DA "EMPLOYEE.DAT" in the Open statement. The EOF function
The operating system automatically automatically appends a special character ch aracter,, called the end-of-file marker, to the end of a sequential file. VB can 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 after the last l ast record has been read – OR – (2) at the th e same time that the last l ast record has been read. COBOL falls fall s into the first category, category, VB falls into the second. FYI: This discussion applies only to how VB processes sequential files – because when VB processes the rows of a database table, it actually handles hand les EOF "the "th e COBOL way". way". In a language that th at recognizes EOF after the last record in the file has h as 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 su bsequent reads occur at the bottom of the th e loop. The pseudocode might be written as follows:
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
READ (first) RECORD DO UNTIL EOF PROCESS THE RECORD
READ (next) RECORD LOOP
In a language that th at recognizes EOF when the last record is read (such as VB), the "input" "inp ut" or "read" " read" loop must be modified so that there is NO PRIMING READ and the read occurs as the FIRST statement in the body of the th e processing processing loop. l oop. The pseudocode might might be written as follows: DO UNTIL EOF READ A RECORD PROCESS THE RECORD
LOOP
The syntax of of the EOF function f unction is EOF(n ) where n is a number corresponding to the file number of the file from which you want to read data. n can either be a hard-coded number n umber or an integer variable, variable, depending on whether or not you used FreeFile in the Open statement. The EOF function can be b e used anywhere that a conditional expression expression can be used; as such, it must always follow keywords such as UNTIL, WHILE, and IF. The EOF function can also be preceded by the keyword 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 and that the input is done at the top of the loop): Do Until EOF(intEmpFileNbr) 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 commadelimited 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 | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT" intEmpFileNbr = FreeFile
Open strEmpFileName For Input As #intEmpFileNbr
Do Until EOF(intEmpFileNbr) EOF(intEmpFileNbr) Input #intEmpFileNbr, strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate
Print strEmpName; _ Tab(25); Format$(intDeptNbr, "@@@@"); _ Tab(35); strJobTitle; _ Tab(55); Format$(dtmHireDate Format$(dtmHireDate , "mm/dd/yyyy"); "m m/dd/yyyy"); _ Tab(70); Format$(Format$(sngHrlyRate, Format$(Format$(sngHrlyRate, "Standard"), "Standard"), "@@@@@@@") Loop
The Close statement When you are finished using a file in your program, you should sh ould Close that file. f ile. The Close statement statement tells VB that you are done using a file, and frees fr ees up the system resources needed needed to process that file. The statement Close #1
frees the resources used by the t he file referenced as #1, and also al so terminates the association association between between the th e Windows-system file and the file number – so at this point, if you wanted to, you could Open some other file AS #1. If you have more more than one file open in a program, you can close multiple multipl e files with one Close statement statement by separating the file fil e numbers with commas: Close #1, #2, #68
The statement Close
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 NotePad for 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 | Vi Visual Basic 6 (VB6)
Download the VB project code for the example above here here..
PDF Writer for VB
www.synactis.com
Create, Cre ate, display, display, print, edit, merge Royalty-free distribution. Try now!
Similar links Creating Advanced PDF documents in VB Creating PDF files in Visual Basic Basic Save the contents of a list box to a file Copy a File Quickly Launch a program from fr om VB Get tag info form a mp3 file Looping through files and putting them in a control Delete A File - Snippet
http://www.vb6.us/tutorials/how-read-simple-text-files
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
Documenting Your VB Code What are databases and why do I care ? 300391 reads
Overflow
Tue, 01/24/2012 - 05:19 — Anonymous (not verified)
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
Thu, 12/29/2011 - 09:02 — Anonymous (not verified)
Thakssssssss reply
Cannot access folder because the path is too long
Sun, 12/18/2011 - 22:16 — tammy (not verified)
Long Path Tool Tool is very ver y useful if you ar e having problems in deleting, de leting, unlocking, copying and even renaming files that ar e 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?
Fri, 12/09/2011 - 20:40 — Rainier (not verified)
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, InStr(ScanString, " ") = 0 Then GetFirstWord = ""
Mon, 11/07/2011 - 23:28 — Anonymous (not verified)
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
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, 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 intPosSave = intPos + 1 End If Loop GetFirstWord = Trim$(Mid$(ScanString, rim$(Mid$(ScanString, intPosSave + 1)) End Function reply
login page
Sun, 09/25/2011 - 10:38 — Anonymous (not verified)
Hi, I am signing signing into my system either as a doctor or a nurse. How would wo uld i show that I have sign in as a doctor/nurse 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 Adodc1.RecordSource = "Select * from login where username = '" + Text1.Text Text1.Text + "'" Adodc1.Refresh If (Adodc1.Recordset.EOF = False) Then If (Text2.Text (Text2.Text = Adodc1.Recordset.Fields("password") Adodc1.Recordset.Fields("password") And Combo1.Text = Adodc1.Recordset.Fields( Adodc1.Recordset.Fields("Class")) "Class")) Then MsgBox "login Success" Unload Me MDIClinic.Show MDIClinic.mnInvoice.Enabled = True MDIClinic.mnConsultation_T MDIClinic.mnConsultation _Treatment.Enabled reatment.Enabled = True MDIClinic.mnPatient_Information.Enabled MDIClinic.mnPatient_Information.En abled = True MDIClinic.mnPatient_Registration.Enabled MDIClinic.mnPatient_Registration .Enabled = True MDIClinic.InvoiceButton.Enabled MDIClinic.InvoiceButton.E nabled = True MDIClinic.SSTab1.Enabled = True
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
MDIClinic.Label14.Caption = Com bo1.Text bo1.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
Sat, 03/19/2011 - 07:35 — Marie Albaugh (not verified)
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, P06.DAT, contains a Sales Person Name and a Sales amo unt in each of its data lines for e very Sales Person of a company. Each data line has two data items as describe below : Items # Description Data Type 1 salesperson name String (maxim um 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 m ust 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 Your name and Assignment Assignment # 2. Print Company Name and Column Headings. 3. Read each data line. 4. You use a Function to calculate calculate Commission Com mission Amount, rounded to decimal places. 5. Compute running running totals for Sales Amount, and Commission Amount. 6. Print Sales Per son Name, Sales Amo unt, and Commission Amount under the heading. 7. At the bottom of the output print Total Sales Amount and Total Commission. that is the assignment 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. He re is a copy of my program that I have so far wasn't sure how to r ound off to the 2 decimal and the floatingpoint I just am not good in the math ma th area and how to do calculation. Any input would be grateful thanks. '----------------------------------------------------------------------------'
How to read simple text files | Vi Visual Basic 6 (VB6) ' Project: Proje ct: 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" "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 e xist") 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, calculateCommission(salesAmt, comm ission) totalSalesAmt = totalSalesAmt + salesAmt totalCommission = totalCommission + commission commission = salesAmt * commission
http://www.vb6.us/tutorials/how-read-simple-text-files
How to read simple text files | Vi Visual Basic 6 (VB6) Console.WriteLine(Space(gap + 1) & Name _ & Format(Name, FMT).PadLeft(13) FMT).PadLeft(13) _ & Format(salesAmt, FMT).PadLeft(12) FMT).PadLeft(12) _ & Form at(commission, FMT).PadLeft(13)) FMT).PadLeft(13)) End While FileClose(1) totalCommission = salesAmt * comm ission Console.WriteLine(Space(gap) & LINE & vbCrLf _ & Space(gap + 1) & "TOTALS:" _ & Format(totalSalesAmt, FMT).PadLeft(12) FMT).PadLeft(12) _ & Format(totalComm ission, FMT).PadLeft(16) FMT).PadLeft(16) _ & vbCrLf & Space(gap) & LINE & vbCrLf & vbCrLf) End Sub '-------------------- Function: calculateCommission() ----------------------------Function Function calculateCommission(ByVal 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 Utility.Round(commission,, 2) 'commission = Math.Round(commission,2) Math.Round(commission,2) 'commission = Math.Floor(salesAmt * comm ission) 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 999.99 Carol Cook 100 1000.00 0.00 Shirley Stew 4575 4575.79 .79 Simple Pimple 499 4999.99 9.99 Horrible Huey 5000.00 Felix Laketr out 5759.53 5759.53 Rickety Pork 100 10000.00 00.00 Peter Popcorn 10000.01 Quickdraw McGraw 12537.87
http://www.vb6.us/tutorials/how-read-simple-text-files
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
Thanks for your time reply
how to open text file with half of its name
Mon, 03/07/2011 - 10:51 — at andy (not verified)
Hi. Can you help me,..? How to open o pen text file with half of its name using vb6. vb6. example ex ample i have 2 files in C:\, they are : 1. Myfile10001.txt Myfile10001.txt 2. Myfile20001.txt Myfile20001.txt I want to rea d file no.2 with 7 characters first (Myfile2xxxx.txt), and ignore nex t characters. my script is : Option Explicit dim file1, file2, astrx astrx = "*" file1 ="c:\Myfile10001.txt" ="c:\Myfile10001.txt" file2 ="c:\Myfile2" & astrx & ".txt" 'this is run Sub OpenTextFile1 Const ForReading = 1, ForWriting = 2, ForAppending ForAppending = 3 Dim fs1, f1 Set fs1 = CreateObject("Scripting.FileS CreateObject("Scripting.FileSystemObject") ystemObject") Set f1 = fs1.OpenTextFile(file1, fs1.OpenTextFile(file1, ForReading,TristateFals ForReading,TristateFalse) e) f1.Close End Sub 'this is error Sub OpenTextFile2 Const ForReading = 1, ForWriting = 2, ForAppending ForAppending = 3 Dim fs2, f2 Set fs2 = CreateObject("Scripting.FileS CreateObject("Scripting.FileSystemObject") ystemObject") Set f2 = fs2.OpenTextFile(file2, fs2.OpenTextFile(file2, ForReading,TristateFals ForReading,TristateFalse) e) f2.Close End Sub reply
How to edit and arrange words in a text file?
Sun, 02/27/2011 - 11:20 — CantEditman (not verified)
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","E orre","14","Freshman","Math","English nglish","Scienc ","Science","History","PE","C:\Johndelatorre.jpeg" e","History","PE","C:\Johndelatorre.jpeg"
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
"Susan Green","13","Freshman" Green","13","Freshman","Math","Engl ,"Math","English","Sc ish","Science","History","Home ience","History","Home Economics","C:\Sus Economics","C:\Susangreen.jpeg" angreen.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 confused with the split function and searching searching for the solution for rearranging this. Please help. T__T reply
Many Thanks
Sun, 02/27/2011 - 10:31 — tonywest (not verified)
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 comm ands. I have re ad through all the tutorials so far and everything make s perfect sense now. As soon as I have read through them all I w ill 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..
Wed, 01/26/2011 - 04:51 — Anudeep (not verified)
How can I read re ad from the middle(any place rather than the starting position) position) of a line in vb. reply
Use the Mid Function
Fri, 01/28/2011 - 10:28 — TMowers (not verified)
To read from anyplace in your line, use the MID function. You have have to know w here you are starting (or you can use the INSTR function for this). Examples of both are shown below. Dim intPosition as integer Dim myString my String as string Dim myOutput m yOutput as string myString = "Mary had a little lamb" intPosition = instr(1,myString, 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 | Vi Visual Basic 6 (VB6)
Alternati Alte rnative ve to APP.PA APP.PATH TH
http://www.vb6.us/tutorials/how-read-simple-text-files
Sun, 01/16/2011 - 12:11 — Muzammal Baig (not verified)
Its work done very well. Just want to add the alternative way to APP.PATH Instead of using (APP.PAT (APP.PATH H & "\") you can use ".\" it will always point to current work ing directory of VB6. i. e. the APP.PATH. This method automatically gets rid of the double "\" problem. You can also also use "..\" to point to the par ent directory o f your APP.PAT APP.PATH. H. Or ".\subdirectory" to point to a sub directory or sub-sub sub-sub directory of App.Path reply
Superb.!!!!!!!!!
Tue, 11/02/2010 - 07:33 — Nishant Pawar (not verified)
Really nice tutorial for beginners...!!!!! reply
how to open msoffice using vb
Sat, 08/28/2010 - 00:06 — balachandar (not verified)
sir ,vb6.0 using sourcecode how to open m sword,msexcel,notepad&msaccess in a single form to split the application display on single form reply
getting data to notepad
Thu, 07/22/2010 - 01:03 — nosebleed (not verified)
data received : 09276578797 8mins data received : 09256578797 3mins data received : 09276578797 8mins i want to get all the number of 0927 to to total the mins... . so the total m inutes of 0927 0927 is 16mins.... how can i make of this project... T_T help me.... reply
instr() is much better than using mid()
Sun, 01/16/2011 - 12:18 — Muzammal Baig (not verified)
use instr(start,string_name_to_be_searched,strin instr(start,string_name_to_be_searched,string g to find) and the full phone number can be found as m any times as you like
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
also instr() will find " " for you so that you know where is the m inutes info info reply
getting data to notepad
Mon, 08/09/2010 - 22:57 — au_simple (not verified)
do you have these data int he notepad or som ewhere else on the form (like listbox)? e ither way, if you know how to read each ea ch entries int he notepad or list, you can use mid() function to see if the value is 0927 then use use same mid() function function to get the number of m inutes and add it. reply
do you have these data int
Mon, 08/09/2010 - 22:56 — au_simple (not verified)
do you have these data int he notepad or som ewhere else on the form (like listbox)? e ither way, if you know how to read each ea ch entries int he notepad or list, you can use mid() function to see if the value is 0927 then use use same mid() function function to get the number of m inutes and add it. reply
thankyou
Tue, 07/06/2010 - 04:20 — RENJINI (not verified)
thankyou reply
conversion
Thu, 04/15/2010 - 15:01 — Daniyal (not verified)
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$ 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 | Vi Visual Basic 6 (VB6)
So Cool ! Tut but how to
http://www.vb6.us/tutorials/how-read-simple-text-files
Wed, 03/03/2010 - 05:46 — Evan Millana (not verified)
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 Text Documents
Mon, 02/08/2010 - 20:22 — enzo (not verified)
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, IIf(Right$(App.Path, 1) = "\", "", "\") 'strTextFileName 'strTextFileName = App.Path & strBackSlash & "Test.txt" "Test.txt" strTextFileName strTextFileName = App.Path & strBackSlash & strFile If Dir$(strTextFileName) Dir$(strTextFileName) <> "" Then Kill strTextFileName strTextFileName End If ' Open Output File intTextFileNbr intTextFileNbr = FreeFile Open strTextFileName For Binary Access Write As #intTextFileNbr 'For lngX = 1 To Len(wString) For lngX = 1 To 255 strCurrentChar = Mid$(wString, Mid$(wString, lngX, 1) Put #intTextFileNbr #intTextFileNbr, , strCurrentChar Next
Tue, 01/26/2010 - 22:53 — pawarvirendra
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
txtTemp.Text txtTemp.Text = Len(wString) Close #intTextFileNbr #intTextFileNbr a: End Sub reply
wow
Thu, 01/21/2010 - 09:48 — Rahul Gandhi (not verified)
what an explanation to the code... Great man! m an! Tons Tons of thanks! thanks! reply
THANKS
Thu, 12/03/2009 - 17:12 — Anonymous (not verified)
THANKS reply
5
Tue, 11/24/2009 - 13:47 — (not verified)
:
2-1- ASP.NET ( Dynamic) 2-2- HTML ( Static)
3-1- SQL Server 3-2- Access
4-1- (C#) 4-2- (VB.NET) 4-3- 6.0 (Visual Basic 6.0) 4-4- (Assembly) 4-5- C C++
5-15-2-
UML ( RUP SSADM (
Rational Rose
...)
. . .)
6-1- Multi Media Builder 6-2- Flash MX
.
24
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
(Forum)
.
.
Demo
.
Document
.
.
reply
This is code is really
Mon, 11/02/2009 - 23:39 — Kiran KK (not verified)
This is code is really helped me a lot to do my project... Thank s... reply
Writing or editing textline
Fri, 10/09/2009 - 20:08 — Anonymous (not verified)
Hello, nice tutorial. Very useful Can you also post writing or editing textline. Thx in advance. jterc reply
I like it
Thu, 07/02/2009 - 08:48 — sage334
Graet lesson, very helpfull Tanks reply
how do u get the app path to
Fri, 06/12/2009 - 03:29 — Anonymous (not verified)
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.
Mon, 05/04/2009 - 22:49 — shekar (not verified)
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
This is the best explanation one could ever give.u rcok m an.. reply
Thank you !
Wed, 03/25/2009 - 17:30 — Alaa Noor (not verified)
Very Nice explaination , much better than what i read in many books thanks a lot sir reply
Wonderful Tutorial, just what we needed
Wed, 02/04/2009 - 11:17 — Ranjith Kumar (not verified)
Wonderful Tutorial, Tutorial, just what we needed..thxs reply
Great
Thu, 01/29/2009 - 09:15 — Anonymous (not verified)
Well done reply
how up load text files
Thu, 12/18/2008 - 23:39 — aruna
how up load text files to sql serve r database by using vb6 reply
how to open using a box like windows explorer
Wed, 11/19/2008 - 15:36 — mikaeel.ghany
how do i allow the user to choose the file to open by using a open box like the one windows uses with windows 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
Mon, 11/10/2008 - 10:54 — Anonymous (not verified)
How to read simple text files | Vi Visual Basic 6 (VB6)
Very Nice Tutorial
http://www.vb6.us/tutorials/how-read-simple-text-files
Sat, 10/25/2008 - 21:33 — LazyPrinzez (not verified)
One thing I really needed neede d for our TLE Project. I'm just a 15-year-old senior high school 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 subjects)--so I sorely needed a tutorial for it. Thank you so much! You don't don't know how much this helps me with our TLE projects and activities! reply
Very Nice Tutorial
Sat, 10/25/2008 - 21:33 — LazyPrinzez (not verified)
One thing I really needed neede d for our TLE Project. I'm just a 15-year-old senior high school 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 subjects)--so I sorely needed a tutorial for it. Thank you so much! You don't don't know how much this helps me with our TLE projects and activities! reply
COOL
Sun, 09/28/2008 - 01:28 — Anonymous (not verified)
i always had problem with opening apps. apps. at least now i can clearly open text o r apps. tnx again reply
EXPORTING
Sat, 09/27/2008 - 19:13 — Anonymous (not verified)
CAN YOU TELL ME HOW TO EXPORT .FRM TO .EXE reply
Open the file in vb6 and go
Wed, 02/11/2009 - 20:58 — Anonymous (not verified)
Open the file in vb6 and go under file to ex port as project name.e xe reply
Thanks THANK YOU SO MUCH !!! It is an outstanding outstanding effort from ur side, It was so helful for m e. God Bless U !!!! reply
Tue, 09/02/2008 - 12:44 — Adnan (not verified)
How to read simple text files | Vi Visual Basic 6 (VB6)
If I only want to get a few
http://www.vb6.us/tutorials/how-read-simple-text-files
Sat, 05/24/2008 - 10:18 — Anonymous (not verified)
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
Sun, 03/09/2008 - 22:20 — Anonymous
Quite helpfull but it does not show how to wirte into file reply
congrats, very good
Mon, 01/14/2008 - 09:17 — Anonymous
congrats, very good 1 Márcio reply
vb6 textboxcontrol
Fri, 11/16/2007 - 23:09 — Anonymous
can u tell me how can i bold or change change the color of the sele cted 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) EOF(nHandle) '// Loop until end of file . Line Input #nHandle, T TextLine extLine '// Read line into varia ble. ' use the TextLine herer here r... Loop Close #nHandle reply
Wed, 08/29/2007 - 11:13 — Anonymous
How to read simple text files | Vi Visual Basic 6 (VB6)
Excellent Tutorial
http://www.vb6.us/tutorials/how-read-simple-text-files
Tue, 08/28/2007 - 23:30 — Anonymous
A great piece of tutorial. Step by step and in a very simple way. Keep it Up Sameer [email protected] reply
Exporting Exporting files fil es
Tue, 07/17/2007 - 18:03 — Anonymous
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
Sat, 06/09/2007 - 21:28 — Anonymous
very very helpful reply
Scenario 2: Fixed-Width ("Print" Format)
Sun, 06/03/2007 - 15:34 — Anonymous
i would like a tutorial that discribes discribes how to re ad a text file with that format. thanks, its a great tutorial. reply
ClaweD`s Answers :D
Sat, 12/15/2007 - 09:50 — ClaweD
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
Mon, 03/10/2008 - 15:37 — Anonymous
How to read simple text files | Vi Visual Basic 6 (VB6)
http://www.vb6.us/tutorials/how-read-simple-text-files
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: -
-
- Lines and paragraphs break automatically.
More information about formatting options
Preview
Unless otherwise noted, all content on this site and in the source samples is Copyrighted © 201 2011 1 by the owner of vb6.us. All rights reserved - Contact Information