Reading Data from File

This short article demonstrates how to open a text file and read the data line by line. The script below opens a text file called "myDataFile.txt" located in the same folder as the FRED .frd file. 

First, the file is read one line at a time and placed into the textLine string variable.

    Dim filename As String, textLine As String
    filename = GetDocDir() & "\" & "myDataFile.txt"

    Open filename For Input As #1

        While Not EOF(1)
            Line Input #1, textLine

            'do something

        Wend

    Close #1

Next, use the ParseString command to parse the textLine data. An expanded version of the script is shown below. Note: In this example, we needed to define two arrays - one for numerical values ("numArray"), and one for strings ("stringArray") - and then the delimiters between adjacent values. We used the BASIC character codes - in this case, for space, tab, and comma.

Run the ParseString function to copy the contents of textLine into both numArray and stringArray.

As an example: 

  • textLine data = 1   0.15   77.5   BK7
  • stringArray = ["1", "0.15", "77.5", "BK7"]
  • numArray = [1, 0.15, 77.5, 0]

StringArray stores the string representations of these values and numArray stores numerical representations (where non-numerical values are represented by a value of 0).

    Dim filename As String, textLine As String
    filename = GetDocDir() & "\" & "myDataFile.txt"

    Dim numArray() As Double
    Dim stringArray() As String
    Dim delimiterString As String
    Dim numItems As Long

    delimiterString = Chr(9) & Chr(32) & Chr(44)    'space, tab, comma

    Open filename For Input As #1

        While Not EOF(1)
            Line Input #1, textLine

            numItems = ParseString(textLine, delimiterString, numArray, stringArray)

            'now actually do something with the data

        Wend

    Close #1

Still need help? Contact Us Contact Us