
80 Logic Programming With Prolog
Example 2
Define a predicate readterms to read the first four terms from a specified file and
output them to another specified file, one per line.
A suitable definition is given below.
readterms(Infile,Outfile):-
see(Infile),tell(Outfile),
read(T1),write(T1),nl,read(T2),write(T2),nl,
read(T3),write(T3),nl,read(T4),write(T4),nl,
seen,told.
Assuming the contents of file textfile.txt are the three lines:
'first term'. 'second term'.
'third term'.
'fourth term'. 'fifth term'.
using readterms gives the following brief output:
?- readterms('textfile.txt','outfile.txt').
yes
and creates a file with four lines of text
first term
second term
third term
fourth term
Although the definition of readterms above is correct as far as it goes, the final
two terms (seen and told) will cause the current input and output streams to be set
to user. This could cause problems if readterms were used as a subgoal in a larger
program where the current input and output streams were not necessarily both user
when it was called.
It is good programming practice to restore the original input and output streams
as the final steps when a goal such as readterms is evaluated. This can be achieved
for input by placing the goals seeing(S) and see(S) before and after the other terms
in the body of a rule. The former binds S to the name of the current input stream;
the latter resets the current input stream to S.
A similar effect can achieved for output by placing the goals telling(T) and
tell(T) before and after the other terms in the body of a rule. The former binds T to
the name of the current output stream; the latter resets the current output stream to
T.
Using these conventions, the revised definition of readterms is as follows: