1
votes

I am learning Prolog using SWI Prolog. Consider the situation in which I have a file named myFile.txt that contains the following content:

line1.
line2.
line3.

Now I am trying to create a predicate that using the read predicate have to read the content of this file, I have create the following predicate:

readFileSee(InputFile) :- seeing(OldStream),
                          see(InputFile),
                          read(Term),
                          write(Term),
                          seen,
                          see(OldStream).

The problem is that, when I execute this program, I obtain only the first line. For example if I launch this statement I obtain:

?- readFileSee('/home/andrea/Documenti/prolog/lezione6/project/myFile.txt').
line1
true.

The read predicate read Prolog terms but why read only the first terms? What can I do to let it read all the terms contained in the file? Can I do it using read predicate?

1
The manual claims that read reads the next term, not all terms in a file. I don't see you call read in a loop or anything, you just call it once. Why would you expect that it reads more than one term?!? - user1812457

1 Answers

2
votes

you can use repeat:

readFileSee(InputFile) :- seeing(OldStream),
                          see(InputFile),
                          repeat,
                          read(Term),
                          ( Term == end_of_file -> true ; 
                            write(Term), fail
                          ),
                          seen,
                          see(OldStream).