KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility method to append to .txt file
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: December 13, 2021

This method inserts a string at the end of a .txt file. The string can be inserted on a new line if the * parameter is used. Note that the file must be writable.

//=========================================
//METHOD: AppendToTxt
//DESCRIPTION: Given a path to a .txt file and a string to append, this method will insert the string at the end of the file. If * parameter is specified, the string will be inserted on a new line. The file must be writable.
//PARAMETERS:
// $1 (Text): Path to .txt file
// $2 (Text): String to append
// $3 (*): If included, append string on new line
//=========================================

var $1; $2 : Text
var $file : 4D.File
var $path; $text; $src; $new : Text

$path:=$1
$text:=$2

$file:=File($path; fk platform path)

If (Count parameters>=2)
   If (($file.isWritable) & ($file.extension=".txt"))
     $src:=$file.getText()
     If (Count parameters=3)
       $new:=$src+"\r"+$text
     Else
       $new:=$src+$text
     End if
     $file.setText($new)
   End if
End if

Below is an example:

$path:=System folder(Desktop)+"Log.txt"
$text:="https://example.website.com HoopsternInc /c/agents?limit=50&id=27"
AppendToTxt($path; $text; *)

Contents of Log.txt before running example:



Contents of Log.txt after running example: