5.3 Dealing with files

XLogo can read and write files, too.

First, the command openflow is used to open a file. Create a text file (using notepbad) called test.txt, and save it to a known location, such as c:\test.txt. Try this command on the command bar:

openflow 2 "c:\\test.txt

The double backslash \\ is necessary. This command opens the file c:\test.txt, and make it file number 2. Inside an XLogo program, opened files are identified by their numbers.

Assuming the file does exist, you can try the following command.

make "v1 readlineflow 2

This reads a line from the file, and make that the content of variable v1. To confirm that variable v1 has the right content, print it out to the output area using the following command:

print :v1

It should print the contents of the first line of the text file.

At the end of the file, the following command prints a value of true.

print endflow? 2

This can, then, be used to control the flow of a program depending on whether it has reached the end of a file.

For example, the following code reads and prints all the lines of a file:

openflow 2 "c:\\test.txt  
while [not endflow? 2] [print readflowline 2]

The while construct is essentially saying “as long as it is not the end of file 2, read a line from file 2 and print it out”. Formally, the while construct expects two lists to follow the keyword. The first list [not endflow? 2] is an expression that indicates whether the program should stay in the loop. The second list [print readflowline 2] encapsulates the actions to perform as long as the first list evaluates to true.