Skip to content

6. Text files

A text file is a file containing lines of text. Let’s examine the creation and use of such files through examples.

6.1. Creation and use

Program
Results

C:\>cscript fic1.vbs

C:\>dir

FIC1     VBS           352  07/01/02   7:07 fic1.vbs
TESTFILE TXT            25  07/01/02   7:07 testfile.txt

C:\>more testfile.txt

This is another test.

Comments

  • Line 7 creates a file object of type "Scripting.FileSystemObject" using the CreateObject("Scripting.FileSystemObject") function. Such an object allows access to any file on the system, not just text files.
  • Line 9 creates a "TextStream" object. The creation of this object is associated with the creation of the testfile.txt file. This file is not designated by an absolute path such as c:\dir1\dir2\....\testfile.txt but by a relative path testfile.txt. It will then be created in the directory from which the command to execute the file is launched.
  • The Windows file system is not aware of concepts such as text files or non-text files. It only recognizes files. It is therefore up to the program that uses this file to determine whether to treat it as a text file or not.
  • Line 9 creates an object using the SET command for assignment. Creating a text file object involves creating two objects:
    • the creation of a Scripting.FileSystemObject (line 7)
    • followed by the creation of a "TextStream" object (text file) using the OpenTextFile method of the Scripting.FileSystemObject, which accepts several parameters:
      • the name of the file to be handled (required)
      • the file access mode. This is an integer with three possible values:
        • 1: read-only mode
        • 2: write mode. If the file does not already exist and if the third parameter is present and has the value true, it is created; otherwise, it is not. If it already exists, it is overwritten.
        • 8: append mode, i.e., writing to the end of the file. If the file does not already exist and the third parameter is present and set to true, it is created; otherwise, it is not.
  • Line 11 writes a line of text using the WriteLine method of the created TextStream object.
  • Line 13 "closes" the file. You can no longer write to or read from it.
  • Line 16 creates a new "TextStream" object to use the same file as before, but this time in "append" mode. The lines that will be written will be appended to the existing lines.
  • Line 18 writes two new lines, noting that the vbCRLF constant is the line-end marker for text files.
  • Line 20 closes the file again
  • Line 23 reopens it in "read" mode: we will read the file's contents.
  • Line 27 reads a line of text using the ReadLine method of the TextStream object. When the file is first "opened," the cursor is positioned on the first line of text. Once this line has been read by the ReadLine method, the cursor moves to the second line. Thus, the ReadLine method not only reads the current line but also automatically "moves" to the next line.
  • To read all lines of text, the ReadLine method must be applied repeatedly in a loop. This loop (line 26) ends when the AtEndOfStream attribute of the TextStream object is set to true. This means there are no more lines to read in the file.

6.2. Error Cases

There are two common error cases:

  • opening a file for reading that does not exist
  • Opening a file for writing or appending to a file that does not exist, with the third parameter set to false in the call to the OpenTextFile method.

The following program shows how to detect these errors:

Program
' Create & fill a text file
Option Explicit
Dim objFile, MyFile
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim errorCode

' Create a file object
Set objFile = CreateObject("Scripting.FileSystemObject")

' Open an existing text file in read mode
On Error Resume Next
Set MyFile = objFile.OpenTextFile("abcd", ForReading)
errorCode = err.number
On Error GoTo 0
If errorCode <> 0 Then
    ' the file does not exist
    wscript.echo "The file [abcd] does not exist"
Else
    ' Close the text file
    MyFile.Close
End If


' open a text file that must exist for writing
On Error Resume Next
Set MyFile = objFile.OpenTextFile("abcd", ForWriting, False)
errorCode = err.number
On Error GoTo 0
If errorCode <> 0 Then
    wscript.echo "The file [abcd] does not exist"
Else
    ' Close the text file
    MyFile.Close
End If

' open a text file that must exist in append mode
On Error Resume Next
Set MyFile = objFile.OpenTextFile("abcd", ForAppending, False)
errorCode = err.number
On Error GoTo 0
If errorCode <> 0 Then
    wscript.echo "The file [abcd] does not exist"
Else
    ' Close the text file
    MyFile.Close
End If

' end
wscript.quit 0
Results
C:\>dir

FIC1     VBS           964  07/01/02   7:54 fic1.vbs
TESTFILE TXT             0  01/07/02   8:18 testfile.txt
FIC2     VBS         1,252  01/07/02   8:23 fic2.vbs
3 file(s)              2,216 bytes
2 directory(ies)        4,007.11 MB free

C:\>cscript fic2.vbs

The file [abcd] does not exist
The file [abcd] does not exist
The file [abcd] does not exist

6.3. The Tax Calculation application with a text file

We return to the tax calculation application, assuming that the data needed to calculate the tax is in a text file named data.txt:

12620 13190 15640 24740 31810 39970 48360 55790 92970 127860 151250 172040 195000 0
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65
0 631 1290.5 2072.5 3309.5 4900 6898.5 9316.5 12106 16754.5 23147.5 30710 39312 49062

The three lines contain, respectively, the data from the application’s limit, coeffR, and coeffN arrays. Thanks to the modular design of our application, changes are made primarily in the getData procedure responsible for constructing the three arrays. The new program is as follows:

Program
' Calculation of a taxpayer's tax
' the program must be called with three parameters: married children salary
' married: character O if married, N if unmarried
' children: number of children
' salary: annual salary without cents

' mandatory variable declaration
Option Explicit
Dim error

' retrieve the arguments and check their validity
Dim wife, children, salary
error = GetArguments(wife, children, salary)
' error?
If error(0) ≠ 0 Then wscript.echo error(1) : wscript.quit error(0)

' retrieve the data needed to calculate the tax
Dim limits, coeffR, coeffN
error = getData(limits, coeffR, coeffN)
' error?
If error(0) ≠ 0 Then wscript.echo error(1) : wscript.quit 5

' Display the result
wscript.echo "tax=" & calculateTax(spouse,children,salary,limits,coeffR,coeffN)

' exit without error
wscript.quit 0

' ------------ functions and procedures

' ----------- getArguments
Function getArguments(ByRef wife, ByRef children, ByRef salary)
    ' must retrieve three values passed as arguments to the main program
    ' an argument is passed to the program without spaces before or after
    ' regular expressions will be used to verify the validity of the data

    ' returns an error array variant with 2 values
    ' error(0): error code, 0 if no error
    ' error(1): error message if an error occurs, otherwise an empty string

    Dim syntax
    syntax = _
    "Syntax: pg married children salary" & vbCRLF & _
    "married: character O if married, N if unmarried" & vbCRLF & _
    "children: number of children (integer >=0)" & vbCRLF & _
    "salary: annual salary without cents (integer >=0)"

    ' Check that there are 3 arguments
    Dim nbArguments
    nbArguments = wscript.arguments.count
    If nbArguments<>3 Then
        ' error message
        getArguments = array(1, "syntax" & vbCRLF & vbCRLF & "error: incorrect number of arguments")
        ' end
        Exit Function
    End If

    Dim pattern, matches
    Set pattern = new regexp

    ' the marital status must be one of the characters oOnN
    pattern.pattern="^[oOnN]$"
    Set matches = template.execute(wscript.arguments(0))
    If matches.count=0 Then
        ' error message
        getArguments = array(2, syntax & vbCRLF & vbCRLF & "error: incorrect 'married' argument")
        ' exit
        Exit Function
    End If
    ' retrieve the value
    If lcase(wscript.arguments(0)) = "o" Then
        marie = true
    Else
        marie = false
    End If

    ' children must be an integer >= 0
    pattern.pattern="^\d{1,2}$"
    Set matches = pattern.execute(wscript.arguments(1))
    If matches.count=0 Then
        ' error
        getArguments = array(3, syntax & vbCRLF & vbCRLF & "error: incorrect children argument")
        ' exit
        Exit Function
    End If
    ' retrieve the value
    children = Int(WScript.Arguments(1))

    ' salary must be an integer >=0
    pattern.pattern="^\d{1,9}$"
    Set matches = pattern.execute(wscript.arguments(2))
    If matches.count=0 Then
        ' error
        getArguments = array(4, "syntax", "\n", "\n", "Error: incorrect salary argument")
        ' exit
        Exit Function
    End If
    ' retrieve the value
    salary = clng(wscript.arguments(2))

    ' it's done without errors
    getArguments = array(0, "")
End Function

' ----------- getData
Function getData(ByRef limits, ByRef coeffR, ByRef coeffN)
    ' The data from the three arrays limits, coeffR, and coeffN are in a text file
    ' named data.txt. Each array occupies a line in the form val1 val2 ... valn
    ' limits, coeffR, and coeffN are found in that order

    ' returns a 2-element error array variant to handle any errors
    ' error(0): 0 if no error, an integer >0 otherwise
    ' error(1): the error message if an error occurs

    Dim objFile, MyFile, errorCode
    Const ForReading = 1, dataFileName="data.txt"

    ' Create a file object
    Set objFile = CreateObject("Scripting.FileSystemObject")
    ' Open the data.txt file for reading
    On Error Resume Next
    Set MyFile = objFile.OpenTextFile(dataFileName, ForReading)
    ' Error?
    errorCode = err.number
    On Error GoTo 0
    If errorCode <> 0 Then
        ' An error occurred - log it
        getData = array(1, "Unable to open the data file [" & dataFileName & "] for reading")
        ' exit
        Exit Function
    End If

    ' Now we assume the content is correct and do not perform any checks
    ' read the 3 lines

    ' limits
    Dim line, i
    line = MyFile.ReadLine
    getDataFromLine line, limits

    ' coeffR
    line = MyFile.ReadLine
    getDataFromLine line, coeffR


    ' coeffN
    line = MyFile.ReadLine
    coeffN = split(line, " ")
    getDataFromLine line,coeffN

    ' close the file
    MyFile.close

    ' finished without errors
    getData = array(0, "")
End Function

' ----------- getDataFromLine
Sub getDataFromLine(ByRef line, ByRef array)
    ' places the numerical values contained in line into array
    ' these are separated by one or more spaces

    ' initially, the array is empty
    array = array()
    ' define a pattern for the line
    Dim pattern, matches
    Set pattern = New RegExP
    With pattern
        .pattern="\d+,\d+|\d+"    ' 140.5 or 140
        .global=true              ' all values
    End With

    ' analyze the line
    Set matches = pattern.execute(line)
    Dim i
    For i=0 To matches.count-1
        ' resize the array
        ReDim Preserve array(i)
        ' a value is assigned to the new element
        array(i) = cdbl(matches(i).value)
    Next

    'End
End Sub




' ----------- calculateTax
Function calculateTax(ByVal spouse, ByVal children, ByVal salary, ByRef limits, ByRef coeffR, ByRef coeffN)

    ' calculate the number of brackets
    Dim nbParts
    If spouse=true Then
        nbParts = (children / 2) + 2
    Else
        nbParts = (children / 2) + 1
    End If
    If children >= 3 Then nbParts = nbParts + 0.5

    ' Calculate the family quotient and taxable income
    Dim income, qf
    income = 0.72 * salary
    qf = income / nbParts

    ' Calculate the tax
    Dim i, tax
    i = 0
    Do While i < ubound(limits) And qf > limits(i)
        i = i + 1
    Loop
    calculateTax = INT(income * coeffr(i) - nbParts * coeffn(i))
End Function

Comments:

  • In the text file data.txt, values may be separated by one or more spaces, making it impossible to use the split function to retrieve the values from the line. A regular expression had to be used
  • The getData function returns, in addition to the three limit arrays, coeffR and coeffN, a result indicating whether an error occurred or not. This result is a Variant array of two elements. The first element is an error code (0 if no error), the second is the error message if an error occurred.
  • The getData function does not validate the values found in the data.txt file. In a real-world scenario, it should do so.