Text files
In the previous chapter, we learned how to work with the text area. If we wanted to create a file, we had to save it using the SaveToFile command. Now we will learn another way to work with text files.
We will use a special kind of data type - TextFile, which indicates a text file stored somewhere on the disk. We will declare the variable of this data type the same way as other variables we have worked with so far. However, this variable will not contain the text file, it will only be a mediator. For a variable to be associated with a file, it must be assigned to it using the AssignFile command (variable, file_name). Then we want to start working with the file. We want to open it first. Now we have to decide whether we will read only or write into that file as well. If we want to read only we can use following commands:
Reset (binary); a file will open, from which we will read only
Readln (variable, string variable); reading the file itself
If we want to write to the file, we will use different commands:
Rewrite (variable); the file we will open, and we can write into it
Writeln (variable, text); writing to a file
We see that there is a difference between opening a file for reading only and writing. One command, however, has both types of commands the same, namely closing the file - CloseFile (variable);. After each work with a file, we must not forget to close it, otherwise the changes will not be made.
We'll show you how to work with a text file on the following example. We use one button to create a file, write a few lines into it, and not forget to close it. The second button opens the file once again, reads the written text, displays it in the text area, and closes it again. At the same time, a text document is created in the project folder (Figures 125 and 126).
We used the command Eof (file) (the abbreviation End Of File), which is looking for the end of the document, so we do not need to know the exact number of rows and all of them will be listed.