5.77 How to create text file and append string to it?

restart; 
try 
   fd :=-1; 
   fd := fopen("C:\\output3.txt",APPEND,TEXT); 
catch: 
   print(`Unable to open file, error is`); 
   print(StringTools:-FormatMessage(lastexception[2])); 
end try: 
 
if not(evalb(fd=-1)) then #file open ok 
   str:="hello world"; 
   try 
      fprintf(fd,"%s\n",str); 
   catch: 
      print(`failed to append to file, error is`); 
      print(StringTools:-FormatMessage(lastexception[2])); 
   finally: 
     close(fd); 
   end try; 
fi: