Skip to content

How to Read or Write a text file

Dr. Nicola Mingotti edited this page Dec 11, 2021 · 1 revision

CAVEAT. This recipe is biased in favour of Linux/Unix systems. If you are not in this OS the file pathnames will look different.

File reading and writing is one of the most basic activity your program needs to do. 90% of the time what you want is just to read the full file from disk ans store it into a local variable. O symmetricaly, store the content of a local variable into the disk for persistence.

Example-1. Read a text file

  • Create a file with your preferred text editor (emacs, vi, nano etc.), for example I create a file called myTest.txt in my home directory /home/p. I write there simply Emacs says: Hello World!, then close the editor.
  • Now I go to Cuis, open a Workspace, type the command and run it.
'/home/p/myTest.txt' asFileEntry fileContents .  " => 'Emacs says: Hello World ! ' "
  • Voila', you know how to get a file content !
  • Exerciee-1. Store your file content in a variable.
  • Exercise-2. Check that what comes out of fileContents is a String.

Example-2 . Write a text file

  • This time we will write a text file with Cuis and then go to check it with our text editor.
  • Let's create a file from Cuis in /home/p/myTest2.txt and write into it Cuis says: Hello World!.
  • Open a Workspace and run this line
'/home/p/myTest2.txt' asFileEntry fileContents: 'Cuis says: Hello World!'. 
  • Ok, now I open my text editor (Emacs) and go to read /home/p/myTest2.txt ... and I see what I was expecting: Cuis says: Hello World!.

Example-3. Append stuff to an existing file

'/home/p/myTest2.txt' asFileEntry  appendContents: 'ord-2Xrecord-3X'.

NM on 11-Aug-2021. Tested in Cuis5.0-4738.image

Clone this wiki locally