File Processing   

 File processing involves three steps: 


Opening a File

The FileOpen command is used to open files.

A sequential file is little more than a file that consists of ASCII characters.

The
FileOpen statement has the following syntax:

FileOpen (fileNumber, pathname, OpenMode)

 The following are the components of the syntax:  

  • filenumber is an integer number. The first file number must be 1, and up to 255 files can be opened simultaneously.  The file number is used to identify the open file to other file I/O commands.

  • pathname is the full path and filename of the file to open.  

  • OpenMode specifies how to open the file.  It can have the values Append, Binary, Input, Output, or Random.  Input specifies to open the file for reading.  Output and Append specify to open the file for writing.  If a file does not exist when it is opened with Output or Append, a new file is created.  The Append option differs from the Output option in that any data written to the file is appended to the end of the file.  Existing files opened with the Output option are overwritten.

  • FileOpen allocates a buffer to perform the file I/O and determines the mode of access to use with the buffer. A buffer is a block of memory the computer sets aside for input and output operations.  

  • For example, assume you want to open a file named VB.TXT in C:\VB using the file number 1. The code required to perform this task looks like the following:

FileOpen(1, "C:\VB\VB.TXT", OpenMode.Input)

If you do not specify the path of the file, Visual Basic will assume that the file you are opening is in the current directory, usually the directory from which your application is executing. 

FileOpen(1, "VB.TXT", OpenMode.Input)

VB.NET does not provide App.Path to specify the directory from which your application is executing (the bin folder), but there are several alternate approaches. 

AppPath = System.IO.Path.GetFullPath("..\")

OR

Public Function App_Path() As String
      Return System.AppDomain.CurrentDomain.BaseDirectory()
End Function

FileOpen(1, App_Path & "VB.TXT", OpenMode.Input)

You can open more than one file at a time. However, you must use different file numbers for each open file.  The FreeFile method returns an Integer value representing the next file number available for use by the FileOpen function.

fileNumber = FreeFile( )
FileOpen(fileNumber, "C:\VB\VB.TXT", OpenMode.Input)


Determining the End of the File

When reading a file, you must know when to stop. Attempting to read past the end of a file will generate an error. Reading less than an entire file may also prove troublesome, depending on your program's needs. 

Visual Basic provides the EOF property that you can use to determine when to stop reading: 

  • EOF returns True when the end of the file is reached.

---------------------

To determine when you have reached the end of a file, use the EOF function, which has the following format:

While Not EOF(filenumber)

where filenumber is the file number of the open file. The EOF function returns True when the end of the file is reached.

---------------------

Visual Basic provides an additional useful function:

  • LOF returns the size in bytes of an open file.

The syntax for LOF is as follows: 

FileSize = LOF(filenumber) 

  • filenumber is the file number of the open file for which you want to obtain the size in bytes.

 


Reading a File 

Reading a file means extracting the characters that are in the file into a memory buffer. To a read a file, you must

  • Determine how many characters to read

  • Provide variables to receive the data

Visual Basic provides several approaches to read a sequential file.  These notes will present the most simple approaches.

---------------------

Input

Input provides an easy way to read a list of numbers or strings from a file and assign them to variables. The syntax for the Input method is: 

Input (fileNumber, variable) 

The following are the components of the syntax:

  • filenumber is the file number of the open file to read.

  • variable is the variable into which you want to read the data

  • Input (fileNumber, quoteDate)

Assume that a file contains the following:

Mark, Wednesday 

Using Input, Mark and Wednesday could be read into local variables Name and DayOfWeek

Input (fileNumber, Name)
Input (fileNumber, DayOfWeek)

Note that the fields in data file are separated by commas. 

---------------------

InputString Function

The InputString function has the following syntax: 

varname = InputString (filenumber, characterCount)

The following are the components of the syntax:

  • varname is the variable to hold the line of data.

  • filenumber is the file number of the open file to read.
     

  • characterCount is the number of characters to read.

The InputString function is used to read any number of bytes from a file into a variable. For instance, the following example uses the Input function to read 10 characters into the string variable lastName

lastName = InputString (1, 10)

If you want to read a complete file into a variable, pass the LOF value as the characterCount.  Unlike the Input function, the InputString function returns all of the characters it reads, including commas, carriage returns, linefeeds, quotation marks, and leading spaces.

---------------------

LineInput  

The LineInput function reads a single line of data at a time.  

The statement will read all the characters until it encounters a carriage return-linefeed sequence and returns all the data up to the carriage return.  

The syntax for LineInput is 

varname = LineInput (fileNumber)

The following are the components of the syntax: 

  • varname is the variable to hold the line of data. 

  •  filenumber is the file number of the open file.

The following example reads an entire line from the file. 

oneLine = LineInput(1)


Writing to a File 

The commands to write to a sequential file are the Print and Write methods, which have the following syntax: 

Public Sub Print( _
   ByVal FileNumber As Integer, _
   ByVal ParamArray Output() As Object _
)

-or-

Public Sub PrintLine( _
   ByVal FileNumber As Integer, _
   ByVal ParamArray Output() As Object _
)

-or-

Public Sub Write( _
   ByVal FileNumber As Integer, _
   ByVal ParamArray Output As Object _
)

-or-

Public Sub WriteLine( _
   ByVal FileNumber As Integer, _
   ByVal ParamArray Output() As Object _
)

Note: The ParamArray keyword indicates that a procedure argument is an optional array of elements of the specified type. ParamArray can be used only on the last argument of an argument list. It allows you to pass an arbitrary number of arguments to the procedure. A ParamArray argument is always passed using ByVal.

Unlike the Print function, the Write function inserts commas between items and quotation marks around strings as they are written to the file. You don't have to put explicit delimiters in the list.

Dim testfile As String = "c:\trash.txt"
FileOpen(1, testfile, OpenMode.Output) ' Open file for output. 
Print(1, "This is a test.") ' Print text to file. 
PrintLine(1) ' Print blank line to file. 
PrintLine(1, "Zone 1", TAB(), "Zone 2") ' Print in two print zones. 
PrintLine(1, "Hello", SPC(1), "World") ' Separate strings with a space. 
PrintLine(1, SPC(5), "5 leading spaces ") ' Print five leading spaces. 
PrintLine(1, TAB(10), "Hello") ' Print word at column 10.
PrintLine(1, "---------------------------")
FileClose(1)

FileOpen(1, testfile, OpenMode.Append) ' Open file for output. 
Write(1, "This is a test.") ' Print text to file. 
WriteLine(1) ' Print blank line to file. 
WriteLine(1, "Zone 1", TAB(), "Zone 2") ' Print in two print zones. 
WriteLine(1, "Hello", " ", "World") ' Separate strings with a space. 
WriteLine(1, SPC(5), "5 leading spaces ") ' Print five leading spaces. 
WriteLine(1, TAB(10), "Hello") ' Print word at column 10
.
FileClose(1)

Dim fileSize As Integer
Dim bigVar As String
FileOpen(1, testfile, OpenMode.Input) ' Open file for input. 
fileSize = LOF(1)
bigVar = InputString(1, fileSize)
txtOut.Text = bigVar
FileClose(1)

 

Demo


Closing a File 

  • When you are finished with the open file, you must close the file.  

  • Closing the file releases the file buffer and returns the file number to the unused pool.  

  • It also flushes the buffer so that all new data for the file is saved.  

FileClose statement has the following syntax: 

FileClose (fileNumber)

  • fileNumber is the file number to close. If you omit fileNumber, all active files opened by the FileOpen function are closed. 

The following code example closes an open file with the file number 1: 

FileClose (1)


Example
 

Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
     Handles btnDisplay.Click
   
     Const vbSpc As String = " "
       
Dim fileNumber As Integer
   
     Dim quoteDate As String
   
     Dim open As Single
   
     Dim high As Single
   
     Dim low As Single
   
     Dim close As Single
   
     Dim volume As Long

   
     fileNumber = FreeFile()
        FileOpen(fileNumber,
App_Path() & "quotes.txt", OpenMode.Input)
   
     While Not EOF(fileNumber)
   
             Input(fileNumber, quoteDate)
   
             Input(fileNumber, open)
   
             Input(fileNumber, high)
   
             Input(fileNumber, low)
   
             Input(fileNumber, close)
   
             Input(fileNumber, volume)
   
             txtQuotes.Text = quoteDate & vbSpc
   
             txtQuotes.Text &= open.ToString & vbSpc
   
             txtQuotes.Text &= high.ToString & vbSpc
                txtQuotes.Text &= low.ToString &
vbSpc
   
             txtQuotes.Text &= close.ToString & vbSpc
   
             txtQuotes.Text &= volume.ToString & vbCrLf
   
     End While

        FileClose(fileNumber)
        fileNumber = FreeFile()

   
     FileOpen(fileNumber, App_Path() & "quotes.txt", OpenMode.Append)
   
     Print(fileNumber, quoteDate)
   
     FileClose(fileNumber)

        Dim bigVar As String
        Dim fileSize As Integer
        fileNumber = FreeFile()
        FileOpen(fileNumber, App_Path() & "quotes.txt", OpenMode.Input)
        fileSize = LOF(fileNumber)
        bigVar = InputString(fileNumber, fileSize)
        FileClose(fileNumber)
        txtQuotes.Text &= vbCrLf
        txtQuotes.Text &= "==============="
        txtQuotes.Text &= vbCrLf
        txtQuotes.Text &= bigVar
End Sub

Private Sub cmdWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles cmdWrite.Click
      Dim fileNumber As Integer
      Dim date1 As String = "11/16/2005"
     
fileNumber = FreeFile()
      FileOpen(fileNumber, App_Path() & "quotes.txt", OpenMode.Append)
      WriteLine(fileNumber, date1, 22.65, 22.8, 20.9, 21.29, 500428)
      FileClose(fileNumber)
End Sub

Demo


Here is a set of tutorials on alternative approaches to reading text files.

  Read a text file
  List a directory
  Read and write large files
  Read and write binary data
 
Watch file system changes