Home > Articles > Programming > Visual Basic

  • Print
  • + Share This
This chapter is from the book

Working with Text Files

Sometimes, you may need to store and retrieve information but not need the power of a database (not to mention the extra coding, configuration, and support files that go along with it). In these cases, a text file may be just the thing you need. In this section, you will learn about a simple type of file: a free-form, sequential text file. Sequential means that the file is accessed one byte after the other in sequence, rather than jumping to a specific location. Free form means that the file has no predefined structure; its structure is entirely up to the programmer.

Sequential Text Files

Suppose that you have a form in which the user must choose salespersons from a list, as shown in Figure 21.3. Your mission is to load the names of each salesperson into a list box so that the user can select these names. You could just put a bunch of AddItem statements in the Form_Load event. However, doing so would be a poor solution because you have hard-coded information in the program. Any time the sales force changed, the program would have to be recompiled. A better solution is to use a text file with the salespersons' names in it. The program then reads the names from the text file and populates the list box.

Figure 21.3

The list box is populated with the contents of a text file.

To create the file itself, you can use a text editor such as Notepad, and place each salesperson's name on a separate line, as shown in Figure 21.4.

Figure 21.4

Data stored in sequential text files can be easily edited.

This process is simple, and the file can be edited by anyone—even if that person doesn't have a database tool. For example, a secretary could maintain this file on a network server, and the application could copy the most recent version at startup. Of course, if you are using a database anyway, you might want to go ahead and place the names of the sales force in a table. However, a standard text file could still be used for importing into the table.


The concept of a shared network file also applies to databases and other documents, which may be useful if everyone on your network uses the same desktop application programs.

Reading from a Sequential Text File

Now that you know how easily you can create a sequential text file, you're ready to write some code to read information from the file. One easy way to process a sequential text file is to read it a line at a time. For the salesperson example described in the preceding section, the steps used for filling up the list box are very straightforward:

  1. Open the file for input.

  2. Read a line from the file, and store it in a variable.

  3. Add the contents of the variable to the list box.

  4. Repeat steps 2 and 3 for each line in the file.

  5. Close the file.

The code for filling up the list box, which is discussed in the following sections, is shown in Listing 21.1.

Listing 21.1  Filling a List Box from a Text File

Sub FillListBox()
  Dim sTemp As String
  Open "C:\DATA\PEOPLE.TXT" For Input As #1
  While Not EOF(1)
 Line Input #1, sTemp
      LstPeople.AddItem sTemp
  Close #1
End Sub

Now, examine the code a little more closely. First, before you read or write information, you must open the file with the Open statement. The Open statement associates the actual filename (PEOPLE.TXT in the example) with a file number. A file number is an integer value used to identify the file to other Visual Basic code:

Open "C:\DATA\PEOPLE.TXT" For Input As #1


In the preceding example, 1 is the file number. However, if you open and close multiple files throughout your program, using this number might not be a good idea. In that case, you should use the FreeFile function, which returns the next available file number, as in the following example:

Dim nFile As Integer
nFile = FreeFile
Open "C:\MYFILE.TXT" for Input As #nFile

After you finish using a file, you should close it with the Close statement (refer to Listing 21.1). This way, you can free up the file number for use with other files.

In addition to providing the filename and number association, the Open statement tells Visual Basic how you intend to use the specified file. (Many different options are available with the Open statement, as discussed in the Help file.)


Before you open a file for input, use the Dir$ function to see whether it actually exists.

The keyword Input indicates that the file will be opened for Sequential Input, which means that you can only move forward through the file in sequence. The act of reading information from the file automatically moves an internal file pointer forward for the next read. The code in Listing 21.1 uses a Line Input statement in a While loop to read information. The first Line Input statement reads the first line, the second Line Input reads the second line, and so on. A line in a file is delimited by an end of line marker, which in Windows is the carriage return character followed by the line feed character. The syntax of the Line Input statement is

Line Input #filenumber,variablename

where filenumber is an open file number and variablename is a string or variant variable. If you try to read more lines of text than are in the file, an error occurs. Therefore, you should use the EOF (end-of-file) function to check whether you have reached the end of file before attempting to read again.

After you open the file, you can choose from several methods of reading information from it. In the example, each name is the only piece of information on each line, so no further processing on the string variable is necessary. However, sometimes you may want to read less than a whole line or store more than one piece of information on a single line. In these cases, you can use the Input # statement or the Input function.

The Input # statement is designed to read information stored in a delimited fashion. For example, the following line of a text file contains three distinct pieces of information: a string, a number, and a date. Commas, quotation marks, and the # symbol are used to delimit the information.


The following line of code correctly reads each item from the file into the appropriate variables:

Input #1, stringvar, intvar, datevar

Remember that the Input # statement looks for those delimiters, so make sure that your Input # statements match the format of the file.

Another method of reading information is the Input function. The Input function allows you to specify the number of characters to read from the file, as in the following example:

'Reads five Character from file number 1

s = Input(5,#1)

Now, compare how each of the methods just discussed would process the same line in a file:

'Assume our file has the following line repeated in it:
"This is a test string."

Dim s As String

Line Input #1, s
's contains the entire string including quotes

Input #1, s
's contains the string without quotes

s = Input(5,#1)
's Contains the first 5 characters ("This)

Writing to a Sequential Text File

One good use of a sequential text file is a log file. For example, I have a scheduler application that runs programs and database updates. I rarely work at the machine on which the scheduler application is running, but I can connect over the network and view the log file to see whether the updates have completed.


You can create batch files, FTP scripts, and many other simple file formats on-the-fly by using sequential text files.

Listing 21.2 is a subroutine called LogPrint, which can be added to your program to log error messages. It writes the error message and date to a sequential text file.

Listing 21.2  Using a Sequential Output File to Build an Application Log

Sub LogPrint(sMessage As String)
  Dim nFile As Integer
  nFile = FreeFile
  Open App.Path & "\ErrorLog.TXT" for Append Shared as #nFile
  Print #nFile,format$(Now,"mm-dd hh:mm:ss") & " – " & sMessage
  Close #nFile
End Sub

Figure 21.5

With a few lines of code, you can add a log file to your application.

The function can be called from an error routine or to inform you of a program event:

LogPrint "The database was successfully opened."

The output of the log file can be viewed with a text editor, as shown in Figure 21.5.

Recall from Listing 21.1 (in the preceding section) that you opened the file in Input mode by using the keyword Input. To write data, you open the file for sequential output. However, instead of using the keyword Output, you use Append. Compare the following two lines of code, each of which opens a file for output:

'Append mode – adds to an existing file or creates a new one
Open "ErrorLog.TXT" for Append as #1

'Output Mode – always creates a new file, erases any existing information
Open "ErrorLog.TXT" for Output as #1

Append mode means that data written to the file is added to the end of any existing data. This is perfect for the log file application because you want to keep adding to the log file. Opening a file for Output means that any existing data will be erased. In either case, the Open statement automatically creates the file if it does not exist. After a file has been opened for Output, you can use a couple of different statements to write information to it. The Print# and Write# statements, described in the next section, provide different formatting options for sequential files.

Using Print and Write

The Print# statement works almost exactly like the Print method (described in Chapter 20, "Accessing the Windows API"), except that instead of going to an onscreen object, the output is routed to the open file. Unless a semicolon or other separator is at the end of the list of things to be printed, a new line is automatically inserted into the file after each print. The syntax of the Print# statement is the following:

Print #filenum,expressions

Another statement, the Write# statement, works like the Print# statement, but automatically adds separators and delimiters. The syntax of the Write# statement is the following:

Write #filenum,expressions

The Write statement is intended for use with the Input# statement, described earlier in the "Reading from a Sequential Text File" section. Some examples of both statements are listed here, and the resulting file is shown in Figure 21.6.

Print #1, "This is an example of Print# and Write#"
Print #1, "Siler","Brian"
Write #1, "Siler","Brian"
Print #1, "Really?", 2*3;Spc(5);"Good.";
Write #1,"Date",1/1/1998,1000*5;
Print #1, vbCrLf & "Bye!"

Figure 21.6

Although Print# gives you more control over output format, Write# adds delimiters for easy retrieval of information.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020