Examples of Files
Example 1:
In the following program, we define a readterms predicate. This predicate is used to read the first four terms from the given files. It outputs those terms to another specified file, one per line.
Assume that textfile.txt contains the three lines of contents as follow:
The following output will be generated using the readterms.
The above creates a file that contains a four line of text.
The above shows that the readterms definition is correct as far as it goes. Due to the final two terms, i.e., seen and told, the current input stream and current output stream to be set to the user. If a large program uses readterms as a subgoal, and when the current input stream and current output stream was called, it was not necessarily both user, then the above definition creates a problem.
When we evaluate the goal readterms, to restore the original input and output streams as a final step, it becomes a good programming practice. In the body of a rule, we can achieve the input using the see(P) and seeing(P). We will put these predicate before and after the other terms. In the starting, P binds to the current input stream name. In the last, it resets the current output stream to P.
In the body of a rule, we can achieve the output using the tell(X) and telling(X). We will put these predicate before and after the other terms. In the starting, X binds to the current output stream name. In the last, it resets the current output stream to X.
By the above conventions, the revised definition of readterms is described below:
Example 2:
To copy the input of characters, we define a copychars predicate at the terminal of the user to a specified file until ! character is entered.
In the following program, the value of current input and output stream is saved and restored by copychars. The copy_character task is left, which is defined recursively in the same way to readin in the first example of Output and Input characters of Example of using characters.
In the following way, use copychars:
This will place the tutoraspire character in the myfile.txt file.