Handling Text Files: OpenTextFile

This function is used to open, close, and write in a text file and read a text file.

This page discusses:

Signature

OpenTextFile(TextFilePath : String, TextFileMode : String) : TextFile

Arguments

NameInput / OutputRequired?TypeComment
TextFilePathInYesStringPhysical path of the file on disk.
TextFileModeInYesStringThree different possible modes:
  • w to write in the file and to create it if it does not exist.
  • a to add text at the end of the file.
  • r to read the file.

ReturnType

TextFile

Example 1: Open Function

To open a file in write mode:

let file (TextFile)
set file = OpenTextFile("e:\tmp\TextFile1.txt","w")

To add lines at the end of the file:

set file = OpenTextFile("e:\tmp\TextFile1.txt","a")

To read a file:

set file = OpenTextFile("e:\tmp\TextFile1.txt","r")

Example 2: Close Function

This function lets you close a text file. It must be called at the end of the execution to free the memory.

let file (TextFile)
set file = OpenTextFile("e:\tmp\TextFile1.txt","w")
...
file->Close()

Example 3: Write Function

This function lets you write in a text file. It replaces the whole text in the file if it was opened in “w” mode; Or it adds the string at the end of the file if it was opened in “a” mode.

let file (TextFile)
let buffer (String)
set file = OpenTextFile("e:\tmp\TextFile1.txt","w")
buffer = "Hello" 
file->Write(buffer)

The function can also use a given format to write parameters values in the file. In this case, it has two input arguments: the format string and a list of parameters. The convention is “#” for a parameter value and “|” for a line feed. All parameter types are allowed. One writes the unit if any.
let parms (List)
parms.Append(` Representation316411704 --- IN_WORK\Integer.1` )
parms.Append(` Representation316411704 --- IN_WORK\Real.1` )
parms.Append(` Representation316411704 --- IN_WORK\String.1` )
parms.Append(` Representation316411704 --- IN_WORK\Length.1` )

set file = OpenTextFile("e:\tmp\TextFile1.txt","w")
buffer = "Integer = # Real = # |String = #|Length = #" 
file->Write(buffer,parms)

/*Then the text file will contain the values of the parameters with the unit:*/

Integer = 5 Real = 10.23
String = Hello
Length = 22mm

Example 4: Read Function

This function lets you read in a text file.

let file (TextFile)
let buffer (String)
set file = OpenTextFile("e:\tmp\TextFile1.txt","r")
set buffer = file->Read()