Visual Basic

Reading and Writing to a File

the page has been updated and more will come

There are different ways to get input data. For example, you can use a text box and Inputbox. Now, we will discuss about reading the input data from a text file and write the processed data to a text file.

Creating the Input Text File

  1. Open Notepad application.
  2. Type each record per line. Use the Enter key to truncate the line.
  3. Save the file as a text file.

Opening the Input File

The items of each record from the data file will be assigned to variables one at a time in the order they appear in the file. So, in the above example, Yun Moh will be the first item to be assigned to a variable.

  1. Choose a reference number between 1 and 255. It will be used to identify a particular file that you open in the program.
  2. Add the following statement to open and establish the connection to the file.

  3. Open "file specification" For Input As #n

    The file specification is the directory and file name that you are opening. And n is the reference number to the data file that you open here. For example:

    Open "us_pop_area.txt" For Input As #1

    will open us_pop_area.txt file as have 1 as its reference number.


Reading Items from the Input File

Once the input data file is open, add the follow statement:

    Input #n, variable_name

where n is the reference number from the Open statement and variable_name is the name of variable that will get the next available input item. In the input data file, each item is separated by commas or line breaks (Enter key).

For example:

Input #1, strState, strPop, strArea

will get three items from the input data file #1 to three variables.

The data type of the variables should be the same as the data type of the items in the input data file. In the example, strPop and strArea could be integer data type.


Closing a Data File

After the intended items are read/written from/to the file, close the file with the following statement:

Close #n

where n is the reference number of the file that you want to close.

Tip: Once you close and open the file again, the computer will read from the first item of the file.


Writing Items to a Text File

  1. Choose a file name that you want to write the items into.
  2. Choose a reference number between 1 and 511. While the file is open, it will be called by the reference number.
  3. Run the following statement:
  4. Open "file specification" For Output As #n

    where file specification is the name of file and its directory if necessary, and n is the reference number.

    For example:

    Open "PopPerSM.txt" For Output As #2


  5. To place items into the data file, use the Write # statement as:
  6. Write #n, variable_name

    where n is the reference to the data file, and variable_name is the variable that has the data to write into the file.

    Tip: If there is an existing item on the file, it will replace it. To avoid it, use Append in replacement of Output in the Open statement.

    Tip: The data type of variable_name will determine how the data will be put into the file. If the variable_name is a numeric, the data will be stored with no leading or trailing spaces. If variable_name is a string, it will be stored with quotation marks around it.

    Tip: You can put more than one item per line by listing multiple variables as:

    Write #n, variable_name1, variable_name2, variable_name3

    Items will be separated by a comma between each item.

    Tip: After each Write # statement is executed, a new line will be added into the file.


  7. After all items are written, close the file.
  8. Close #n


Adding Items to a File

  1. Choose a file reference number from 1 to 511.
  2. Use the following statement:

    Open "file specification" For Append As #n

  3. Add data with Write # statement.
  4. After finishing adding items, close the file.


Deleting a File

Kill "file specification"

will delete the file from the disk. The file has to be closed prior to this statement.


Changing a File Name

Name "old file specification" As "new file specification"

will rename the file. The file has to be closed prior to this statement.



Example 1:

The following program reads state population and area from a text file, and calculates population per square mile. At the end, it adds the information to a text file.

Create a Notepad file with the following content, and name it as us_pop_area.txt

The first column is names of states. The second column is populations, and the third column is square miles of the state.

"New Hampshire",1235786,8969
"New Jersey",8414350,7419
"New Mexico",1819046,121364
"New York",18976457,47224
"North Carolina",8049313,48718
"North Dakota",642200,68994
"Rhode Island",1048319,1045
"South Carolina",4012012,30111
"South Dakota",754844,75896
"West Virginia",1808344,24087
"District of Columbia",572059,61


Use the following names and controls for GUI:


Here is the code:

' This program reads population and area of each
' state, and calculates population for sq. mile.

Option Explicit

' main procedure
Private Sub cmdDisplayData_Click()
   Dim strState As String, strPop As String, strArea As String
   Dim sngPopulationPerSquareMile As Single
   strState = cboState.Text
   Call GetPopAndArea(strState, strPop, strArea)
   sngPopulationPerSquareMile = CalculatePopulationPerSquareMile(strPop, strArea)
   Call Display(strPop, strArea, sngPopulationPerSquareMile)
   Call WriteToFile(strState, strPop, strArea, sngPopulationPerSquareMile)
End Sub

' add state names from data source file to combo box.
Private Sub Form_Load()
   Dim strState As String, strPop As String, strArea As String

   ' open the data source file as #1.
   Open "us_pop_area.txt" For Input As #1

   ' read and add from #1 file until it (1) reaches the end of the file.
   Do While Not EOF(1)
      Input #1, strState, strPop, strArea
      cboState.AddItem strState

   Close #1
End Sub

' get and return population and area of the selected state
Private Sub GetPopAndArea(strStateSelcted As String, _
         strPopulation As String, strSquareMile As String)

   Dim strState As String, strPop As String, strArea As String

   Open "us_pop_area.txt" For Input As #1

   ' search for the matching state
   Do While (Not EOF(1)) And (strStateSelcted <> strState)
      Input #1, strState, strPop, strArea

   Close #1

   ' return populatoin and area of selected state
   strPopulation = strPop
   strSquareMile = strArea
End Sub

'calulate and return square mile per person
Private Function CalculatePopulationPerSquareMile(strPopulation As String, _
         strSquareMile As String) As Single
   CalculatePopulationPerSquareMile = strPopulation / strSquareMile
End Function

' display the state population, area and population per sq. mile
Private Sub Display(strPop As String, strArea As String, _
         sngPopulationPerSquareMile As Single)
   txtPop.Text = FormatNumber(Val(strPop), 0)
   txtArea.Text = FormatNumber(Val(strArea), 0)
   txtPopPerSqMile.Text = FormatNumber(sngPopulationPerSquareMile, 0)
End Sub

' create and write the state information to a text file.
Private Sub WriteToFile(strState As String, strPop As String, _
         strArea As String, sngPopulationPerSquareMile As Single)

   Open "PopPerSM.txt" For Append As #2 '*** use Output instead of Append to replace the current record
   Write #2, strState, Val(strPop), Val(strArea), sngPopulationPerSquareMile
   Close #2

End Sub


The answer key: Here is the form file of the finished program. (Also, for in case, the input text file is available)